我有一些与.NET Core依赖项注入和IDisposable EF工作单元对象有关的问题。
我的UnitOfWork实施:
public interface IUnitOfWork : IDisposable
{
...
}
public class UnitOfWork : IUnitOfWork
{
private bool disposed = false;
private readonly MyAppDbContext context;
public UnitOfWork(MyAppbContext context)
{
this.context = context;
}
...
public Task<int> CommitAsync(CancellationToken cancellationToken = default)
{
return this.context.SaveChangesAsync(cancellationToken);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (this.disposed)
return;
if (disposing)
this.context.Dispose();
this.disposed = true;
}
~UnitOfWork()
{
this.Dispose(false);
}
}
DI的注册:
services.AddDbContext<MilkyWayDbContext>(options => ...);
services.AddScoped<IUnitOfWork, UnitOfWork>();
所以我的问题是:
1)UnitOfWork是否应该是IDisposposable?我认为.NET Core DI会在需要时自行处理Context(services.AddDbContext)吗?
2) should I dispose DbContext if I would use services.AddDbContextPool<MilkyWayDbContext>(options => ...)
?
3)如果IUnitOfWork还实现IAsyncDisposable,DI将使用DisposeAsync代替Dispose?
我知道很多人说工作单元模式是反模式,这不在我的问题范围内:)