我这样做对吗?内存使用或性能是否存在问题?
UPD:已处理上下文的错误已修复。
我将 Unity 与工作单元模式一起使用。当我第一次运行我的应用程序时,一切都按预期工作,但是一旦我刷新页面,应用程序就会崩溃,并出现以下异常:
操作无法完成,因为 DbContext 已被释放。
我的 DI 配置如下所示:
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
container.RegisterType<DataContext>();
container.RegisterType<IUnitOfWorkFactory, UnitOfWorkFactory>();
container.RegisterType<IUnitOfWork, UnitOfWork>();
container.RegisterType<IProductRepository, ProductRepository>();
return container;
}
我的UnitOfWork
和UnitOfWorkFactory
看起来像这样:
public class UnitOfWork : IUnitOfWork
{
private readonly IUnityContainer _container;
private bool _disposed;
public UnitOfWork(IUnityContainer container)
{
_container = container;
Context = _container.Resolve<DataContext>();
}
internal DataContext Context { get; set; }
public TRepository GetRepository<TRepository>()
where TRepository : class
{
return _container.Resolve<TRepository>();
}
public void Commit()
{
Context.SaveChanges();
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
Context.Dispose();
}
}
}
public class UnitOfWorkFactory : IUnitOfWorkFactory
{
private readonly IUnityContainer _container;
public UnitOfWorkFactory(IUnityContainer container)
{
_container = container;
}
public IUnitOfWork CreateUnitOfWork()
{
return _container.Resolve<UnitOfWork>();
}
}
UnitOfWork
包含一个GetRepository
允许返回任何存储库的方法。以下是此类存储库的示例:
public class ProductRepository : BaseRepository<Product>,
IProductRepository
{
public ProductRepository(UnitOfWork unitOfWork)
:base(unitOfWork)
{
}
public Product Create(Product entity)
{
return DataBase.Add(entity);
}
public Product Remove(Product entity)
{
return DataBase.Remove(entity);
}
public Product Get(Int32 entityId)
{
return DataBase.FirstOrDefault(x => x.Id == entityId);
}
}
public class BaseRepository<TEntity>
where TEntity : class
{
internal BaseRepository(UnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
internal UnitOfWork UnitOfWork { get; private set; }
internal virtual IDbSet<TEntity> DataBase
{
get { return UnitOfWork.Context.Set<TEntity>(); }
}
}
我的 MVC 控制器依赖于IUnitOfWorkFactory
. 以下是AccountController
示例:
public class AccountController : Controller
{
private readonly IUnitOfWorkFactory _unitOfWorkFactory;
public AccountController(IUnitOfWorkFactory unitOfWorkFactory)
{
_unitOfWorkFactory = unitOfWorkFactory;
}
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
using (var uow = _unitOfWorkFactory.CreateUnitOfWork())
{
var rep = uow.GetRepository<IProductRepository>();
var prod = rep.GetById(1);
}
return View();
}
}