当 Ninject 用作依赖解析器时,如何在 asp.net mvc3 应用程序中处置 DbContext(或对象)
对于这个演示,我创建了一个假数据库+存储库,如下所示
假数据库+存储库
public interface IDemoRepository
{
string[] GetUsers();
}
public class DemoRepository : IDemoRepository, IDisposable
{
public string[] GetUsers()
{
string[] Users = { "Robert","Linda","Jack"};
return Users;
}
public void Dispose()
{
//do nothing
throw new Exception("Disposed is called");
}
}
我的控制器看起来是这个
public class TestController:Controller
{
protected IDemoRepository _repository;
public BaseController(IDemoRepository repository)
{
_repository = repository;
}
public ActionResult()
{
var users = _repository.GetUsers();
Return View(users);
}
}
Ninject部分
我从NUGet安装了ninject并添加了以下代码来解析存储库
kernel.Bind<IDemoRepository>().To<DemoRepository>()
Ninject没有调用DemoRepository.Dispose
,我添加了一个断点,即使我当前的代码抛出错误,但 Ninject 没有调用 DemoRepository.Dispose。
任何人都可以建议我如何处置该物体吗?
For this Demo I have created a fake Database+repository as below
Fake Db + Repository
public interface IDemoRepository
{
string[] GetUsers();
}
public class DemoRepository : IDemoRepository, IDisposable
{
public string[] GetUsers()
{
string[] Users = { "Robert","Linda","Jack"};
return Users;
}
public void Dispose()
{
//do nothing
throw new Exception("Disposed is called");
}
}
My Controller looks this
public class TestController:Controller
{
protected IDemoRepository _repository;
public BaseController(IDemoRepository repository)
{
_repository = repository;
}
public ActionResult()
{
var users = _repository.GetUsers();
Return View(users);
}
}
Ninject Part
I installed ninject from NUGet and added below code for resolving repositories
kernel.Bind<IDemoRepository>().To<DemoRepository>()
Ninject is not calling DemoRepository.Dispose
, i added a break point even my current code is throwing error but Ninject is not calling DemoRepository.Dispose
.
Can any body suggest me how dispose the object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望将其释放,请确保您的存储库已绑定到 Ninject 中的请求范围:
Make sure that your repository is bound to the request scope in Ninject if you want it to be disposed:
您不需要对
DbContext
进行Dispose()
,因为它本身已经正确管理所有连接。这是来自 ASP.NET MVC 技巧 #34 – 处置您的 DataContext(或不处置):You don't need to
Dispose()
of youDbContext
, since it already manages all connections properly itself. Here's a quote from ASP.NET MVC Tip #34 – Dispose of Your DataContext (or Don’t):