我有一个用 asp.net mvc 制作的 Web 应用程序,我正在使用 Ninject 来绑定(bind)接口(interface)。
现在,我有这个:
// Db Context
kernel.Bind<DbContext>().To<DbEntities>().InRequestScope();
// Repositories - which are using instance of DbEntities
kernel.Bind<ICustomerRepository>().To<CustomerRepository>();
kernel.Bind<IProductRepository>().To<ProductRepository>();
// Services - which are using instances of Repositories
kernel.Bind<ICustomerService>().To<CustomerService>();
kernel.Bind<IProductService>().To<ProductService>();
我将 DbContext 绑定(bind)到 RequestScope 中的 DbEntities,因为我想在同一个 Web 请求中使用同一个 DbContext。之后它应该处理它。
但是其他绑定(bind)应该如何呢?默认情况下如何?
例如 IProductRepository
有一个 DbContext
的实例(每个请求一个),也应该是 InRequestScope()
吗?
IProductService
有一个 IProductRepository
绑定(bind)应该如何适合网络应用程序? (而且我不会使服务器的内存过载)
最佳答案
对于 MVC 应用程序,您的配置没问题。如果您在默认 transient 范围或请求范围内绑定(bind)您的存储库,则不会有太大区别。正如 @Mark 在 transient 范围内所述,您的依赖项将作为有界对象的新实例注入(inject),但在事务范围内,它们将根据请求创建一次。如果您想在您的存储库上执行(例如)一些按请求缓存,我更喜欢更多的请求范围并推荐它。
关于c# - Ninject Web 应用程序 : All bindings should be InRequestScope()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13393883/