在存储库实例中实例化 DbContext
在 ASP.NET MVC3 应用程序中,我的控制器将使用一组 BL“管理器”类,而这些类又将使用存储库。这些存储库依赖 EF DbContext 实例来履行其职责。
我计划配置 IoC 容器以通过以下方式进行依赖项注入(在数据模块中)
Bind<StoreContext>().ToSelf().InRequestScope();
Bind<ICatUserRepository>().To<GenericUserRepository>().InRequestScope();
StoreContext
是一个 DbContext
。它通过构造函数注入到 GenericUserRepository 中。 这样,我假设 我的 DbContext 在 PerRequest 中实例化的规则将保持满足,对吗?
In ASP.NET MVC3 application, my controllers will work with the set of BL "manager" classes, which, in turn, will make use of repositories. These repositories rely on EF DbContext instances to perform its duties.
I am planning to configure IoC container to do a dependency injection the following way (in data module)
Bind<StoreContext>().ToSelf().InRequestScope();
Bind<ICatUserRepository>().To<GenericUserRepository>().InRequestScope();
StoreContext
is a DbContext
. It is constructor-injected into a GenericUserRepository
.
This way, I assume, the rule of my DbContext to be instantiated in also PerRequest will remain fulfilled, right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,肯定会这样 - 由于
ICatUserRepository
是在请求范围级别上解析的,IoC 容器将在此时(对于每个请求)创建一个新的GenericUserRepository
实例。构造函数注入的依赖项。解决
StoreContext
依赖关系意味着 IoC 容器将遍历StoreContext
的绑定,检查是否已经存在StoreContext
实例对于当前请求,如果没有创建一个新的副本来注入 - 在您的情况下,这意味着您会为每个新请求获得一个新的StoreContext
实例。Yes it certainly would be - since
ICatUserRepository
is resolved on a request scope level the IoC container will at that point (for each request) create a new instance ofGenericUserRepository
after resolving its dependencies for constructor injection.Resolving the the
StoreContext
dependency means the IoC container will go through the binding forStoreContext
, check if there already is an existing instance ofStoreContext
for the current request and if not create a fresh copy to inject - In your case that means you get a new instance ofStoreContext
for each new request.