ASP.NET MVC、Ninject、多个构造函数的每个请求单个实例
我试图通过将工作单元实例传递到我的存储库来实现工作单元模式。
相关代码来自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>();
}
}
存储库构造函数:
public class ProductRepository {
IUnitOfWork unitOfWork;
public ProductRepository(IUnitOfWork unitOfWork) {
this.unitOfWork = unitOfWork;
}
}
public class CategoryRepository {
IUnitOfWork unitOfWork;
public CategoryRepository(IUnitOfWork unitOfWork) {
this.unitOfWork = unitOfWork;
}
}
我想要的是每个请求最多创建 1 个 SqlUnitOfWork
实例,并传递到我的存储库中(通过它们各自的构造函数)。
IUnitOfWork
绑定上的 InRequestScope()
方法是否足够?如果不是我怎样才能实现这个目标?
Im trying to implement an unit of work pattern by passing an unit of work instance into my repositories.
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;
}
}
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).
Is the InRequestScope()
method on the IUnitOfWork
binding enough? If not how can i achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您拥有的代码可以正常工作。只会将一个
IUnitOfWork
实例提供给请求它的任何类(通过构造函数/属性注入或调用内核的.Get<>
等)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.)