我一直在阅读很多文章,解释如何设置实体框架,DbContext以便每个HTTP Web请求只使用各种DI框架创建和使用一个.
为什么这首先是一个好主意?使用这种方法有什么好处?在某些情况下这是个好主意吗?在使用DbContext存储库方法调用实例化s 时,您是否可以使用此技术执行某些操作?
我对使用Autofac的实现中的Dispose()方法有点困惑IDisposable
说我的对象有一定的深度:
Controller取决于IManager;Manager取决于IRepository;Repository取决于ISession;ISession是IDisposable.这导致以下对象图:
new Controller(
new Manager(
new Repository(
new Session())));
Run Code Online (Sandbox Code Playgroud)
我是否还需要使我的Manager和Repository实现IDisposable,并在Controller中调用Manager.Dispose(),在Manager中调用Repository.Dispose()等,或者Autofac会自动知道我的调用堆栈中哪些对象需要正确处理?Controller对象已经是IDisposable,因为它派生自基本ASP.NET Web API控制器
.net dependency-injection idisposable inversion-of-control autofac
首先,让我们看看微软对Asp.Net Core的默认依赖注入服务的看法:
该框架负责创建依赖项实例,并在不再需要它时将其处置。
即框架将调用类Dispose方法(假设该类实现IDisposable)
其次,DbContext类确实确实实现了IDisposable。
第三,在我们的Startup.cs类中,我们通过AddDbContext方法添加DbContext,默认情况下,该方法将作为Scoped实例添加(即,我们的DbContext被创建并在每个单个请求上进行垃圾回收)。
每个请求一次创建范围的生命周期服务。
例如
public void ConfigureServices(IServiceCollection services)
{
services
.AddDbContext<TheStoreDbContext>(ConfigureDbContext)
.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
}
Run Code Online (Sandbox Code Playgroud)
结论,我们不需要在Asp.net Core应用程序中的任何位置显式调用context.Dispose()。
那么,为什么在线上和教程中有如此多的示例向您显示必须在Repository或UnitOfWork类中实现IDisposable?
例如
public class UnitOfWork : IUnitOfWork
{
private readonly DbContext _context;
public IProductRepository ProductRepository { get; }
public UnitOfWork(DbContext context)
{
_context = context;
ProductRepository = new ProductRepository(context);
}
public void Dispose()
{
_context.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
你怎么看?这是一个有效的问题吗?不在任何地方显式调用Dispose()方法是否有意义?
c# ×2
.net ×1
asp.net ×1
asp.net-core ×1
autofac ×1
dbcontext ×1
idisposable ×1
unit-of-work ×1