ASP.NET MVC,Ninject,每个请求的多个构造单个实例 [英] ASP.NET MVC, Ninject, single instance per request for multiple constructors
问题描述
我试着通过传递工作实例的单位到我的仓库来实现工作模式的一个单位。
Im trying to implement an unit of work pattern by passing an unit of work instance into my repositories.
从相关的Global.asax code。
Relevant code from Global.asax.
public class SiteModule : NinjectModule
{
public override void Load() {
Bind<IUnitOfWork>().To<SqlUnitOfWork>()
.InRequestScope()
.WithConstructorArgument("connectionString", ConfigurationManager.ConnectionStrings["Entities"].ConnectionString);
Bind<IProductRepository>().To<ProductRepository>();
Bind<ICategoryRepository>().To<CategoryRepository>();
}
}
结果
资源库的构造函数:
Repository constructors:
public class ProductRepository {
IUnitOfWork unitOfWork;
public ProductRepository(IUnitOfWork unitOfWork) {
this.unitOfWork = unitOfWork;
}
}
public class CategoryRepository {
IUnitOfWork unitOfWork;
public CategoryRepository(IUnitOfWork unitOfWork) {
this.unitOfWork = unitOfWork;
}
}
结果
我要的是一个最大的 SqlUnitOfWork
每请求创建的1个实例和传递到我的存储库(通过它们各自的构造函数)。
What i want is that a maximum of 1 instance of SqlUnitOfWork
is created per request and is passed into my repositories (via their respective constructors).
是 InRequestScope()
在 IUnitOfWork
结合不够方法是什么?如果不是我怎么能做到这一点?
Is the InRequestScope()
method on the IUnitOfWork
binding enough? If not how can i achieve this?
推荐答案
在code你必须将正常工作。只有一个实例 IUnitOfWork
将给予请求它(通过构造函数/属性注射或调用任何类内核的不用彷徨&LT;&GT;
等)
The code you have will work fine. Only one instance of IUnitOfWork
will be given to any class that requests it (via constructor/property injection or calls to the kernel's .Get<>
etc.)
这篇关于ASP.NET MVC,Ninject,每个请求的多个构造单个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!