我一直在阅读很多文章,解释如何设置实体框架,DbContext
以便每个HTTP Web请求只使用各种DI框架创建和使用一个.
为什么这首先是一个好主意?使用这种方法有什么好处?在某些情况下这是个好主意吗?在使用DbContext
存储库方法调用实例化s 时,您是否可以使用此技术执行某些操作?
我有一个MVC 3 Web应用程序,我使用Entity Framework进行数据访问.此外,我简单地使用了存储库模式,例如,所有与产品相关的东西都在"ProductRepository"中处理,所有与User相关的东西都在"UserRepository"中处理.
因此,我使用UNITY容器来创建DataContext的单例实例,我将其注入每个存储库.快速搜索Google,每个人都建议您不要使用DataContext的单例实例,因为它可能会在将来给您带来一些内存泄漏.
所以,受这篇文章的启发,为每个Web请求创建一个DataContext的单例实例就是答案(如果我错了,请纠正我!)
但是,UNITY不支持"Per-web-request"终身经理.但是,可以实现自己的自定义生命周期管理器,它可以为您处理此问题.实际上,这篇文章对此进行了讨论:
Unity中的Singleton Per Call上下文(Web请求)
问题是,我现在已经实现了上面帖子中描述的自定义生命周期管理器,但我不确定这是否是这样做的方法.我也想知道在提供的解决方案中处理datacontext实例的位置?我错过了什么吗?
实际上有更好的方法来解决我的"问题"吗?
谢谢!
以下是我的Global.asax,Controller和Repository的片段.这清楚地说明了我的实施情况.
Global.asax中
var container = new UnityContainer();
container
.RegisterType<ProductsRepository>(new ContainerControlledLifetimeManager())
.RegisterType<CategoryRepository>(new ContainerControlledLifetimeManager())
.RegisterType<MyEntities>(new PerResolveLifetimeManager(), dbConnectionString)
Run Code Online (Sandbox Code Playgroud)
调节器
private ProductsRepository _productsRepository;
private CategoryRepository _categoryRepository;
public ProductsController(ProductsRepository productsRepository, CategoryRepository categoryRepository)
{
_productsRepository = productsRepository;
_categoryRepository = categoryRepository;
}
public ActionResult Index()
{
ProductCategory category = _categoryRepository.GetProductCategory(categoryId);
.
.
.
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_productsRepository.Dispose();
_categoryRepository.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
产品库
public class ProductsRepository : IDisposable
{
private …
Run Code Online (Sandbox Code Playgroud) entity-framework ioc-container unity-container asp.net-mvc-3