首页 > 解决方案 > .NET Core DbContext Dependency Resolution Scope

问题描述

I am experiencing an issue where DbContext instance injected into a controller is different than the instance injected into a service.

Below is my DbContext registration:

services.AddDbContext<CRMContext>();
services.AddScoped<IEstimateRepository, EstimateRepository>();
services.AddScoped<IMaterialRecordRepository, MaterialRecordRepository>();

My understanding is that by default, AddDbContext adds the context as Scoped, so I would expect that the controller and service would share the same instance.

For reference, here is the controller constructor and the service:

public LineItemController(IEstimateRepository repository)
{
        _estimateRepository = repository;
}

public VentChuteLineItemRequiredEventHandler(IEstimateRepository estimateRepository, IMaterialRecordRepository materialRepository)
        {
            _materialRepository = materialRepository;
            _estimateRepository = estimateRepository;
        }

I am also using Autofac in this application, however as far as I can tell it is not in any way related to the problem at hand. It seems to be just a fundamental misunderstanding on my part of how the scoped lifetime of the DbContext is handled.

标签: c#dependency-injection.net-coreentity-framework-coredbcontext

解决方案


该问题最终与我用来创建相关服务实例的静态类有关。

public static class DomainEventHandler
{
    public static ILifetimeScope _container { get; set; }

    public static void Raise<T>(T args) where T : IDomainEvent
    {
        foreach (var handler in _container.Resolve<IEnumerable<IHandle<T>>>())
        {
            handler.Handle(args);
        }
    }
}

由于 DomainEventHandler 类是静态的,我假设 .net 核心依赖解析器知道它包含的任何实例的生命周期与请求不匹配,因此创建了一个新的 DbContext 实例供它使用。

将此类重构为不再是静态的可以解决该问题。


推荐阅读