c# - .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.
解决方案
该问题最终与我用来创建相关服务实例的静态类有关。
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 实例供它使用。
将此类重构为不再是静态的可以解决该问题。
推荐阅读
- text - 如何仅将段落的一部分加粗?
- twitter-bootstrap - 如何使用自定义(布局和表单)组件制作引导模式
- sql - View using dynamic tables
- python - Pandas 多个过滤器 str.contains 或不包含
- python - 无法理解 Python Negative List Slice 的输出
- python-3.x - importing libraries on Python 3.7
- laravel - 如何使用相关表中的数据过滤查询结果?
- c# - How to switch views in a UWP application
- javascript - 搜索结果不会移动到网站的第一列 - HTML5 搜索
- java - Spring FeignClient:如何配置像 Ribbon 这样的负载均衡器