我已经使用带有 ninject 注入(inject)的实体和存储库模式构建了我的网站。我的问题是我的连接似乎没有得到处理。我有大约 30 个存储库(每个表一个),并且我很快就能得到 sql 过期超时。我无法使用常规的 using 语句,因为代码只能识别注入(inject)之前的接口(interface)。 (在每个 Controller 中,我都有通过 ninject 注入(inject)的存储库接口(interface)实例)。
我在网上搜索过,但找不到适合我的解决方案。 谁能帮帮我吗? 代码示例:
这是在 ninject Controller 中的 addBindings() 下:
ninjectKernel.Bind<IMovieRepository>().To<MovieRepository>().InRequestScope();
以及我的存储库之一:
public class MovieRepository : IMovieRepository, IDisposable
{
private Entities dataContext = new Entities();
public System.Data.Entity.DbContext DbContext
{
get { return dataContext ?? (dataContext = new Entities()); }
}
public void Dispose() { dataContext.Dispose(); }
}
在 Global.asax 文件中:
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory() as IControllerFactory);
最佳答案
我猜测您的存储库(因此大概是您的 DbContexts)被绑定(bind)在 transient 范围内,我相信这意味着每次 Ninject 需要在某处注入(inject)一个时都会创建一个新的存储库。我不确定,但我猜测这些都会在您的应用程序的整个生命周期中保留下来,并且可能不会被处置。
尝试在请求范围内绑定(bind)您的存储库,以便根据网络请求创建和处置它们。
例如
Bind<IFooRepository>().To<ConcreteFooRepository>().InRequestScope();
来自Ninject wiki :
There are four built-in scopes available in Ninject:
- Transient - A new instance of the type will be created each time one is requested. (This is the default scope). Binding method is .InTransientScope()
- Singleton - Only a single instance of the type will be created, and the same instance will be returned for each subsequent request. Binding method is .InSingletonScope()
- Thread - One instance of the type will be created per thread. Binding method is .InThreadScope()
- Request - One instance of the type will be created per web request, and will be destroyed when the request ends. Binding method is .InRequestScope()
关于entity-framework-4.1 - 实体和存储库模式与 ninject、Dispose Issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10257257/