在 Ninject 中处理绑定对象
我在 Global.ascx 中绑定类 DonorContext (派生自 EntityFramework 的 DbContext)的对象,如下所示。
kernel.Bind<DonorContext>().ToSelf().InRequestScope().OnDeactivation(DisposeDonorContext);
我期望在请求结束时,Ninject 将调用 DisposeDonorContext 方法。但它永远不会被调用。
我从网上收集到的是,IDisposible 类型的对象在超出范围时将自动调用其 Dispose 方法。这在我的情况下没有发生,因此我尝试使用 OnDeactivation() 来处置 DonorContext (这也没有发生)。
有什么想法为什么没有发生处置吗?
I am binding an object of class DonorContext (which derives from DbContext of EntityFramework) as below in Global.ascx as below.
kernel.Bind<DonorContext>().ToSelf().InRequestScope().OnDeactivation(DisposeDonorContext);
I was expecting that at end of request, Ninject will call the DisposeDonorContext method. But it never gets called.
What I could gather from web was that the objects of IDisposible types will automatically get their Dispose method called when they go out of scope. This is not happening in my case and hence I was trying the OnDeactivation() to dispose the DonorContext (which doesn't happen either).
Any ideas why the dispose is not happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Ninject 会自动调用实现 IDisposable 的对象的 Dispose 方法(至少我用最新版本测试时是这样)。如果您没有发生这种情况,我怀疑问题在于您从未在应用程序中的任何地方使用此
DonorContext
。所以它永远不会被实例化,也永远不会被处置。例如,如果您有一个控制器将此上下文作为构造函数参数:它应该可以工作。如果您有一个服务层将此上下文作为构造函数参数,然后在控制器中使用此服务(通过构造函数注入),它也会起作用。归根结底,您必须有一个控制器,它需要一些依赖项,该依赖项本身可能是 DonorContext 或其他一些依赖项,这些依赖项本身依赖于 DonorContext(存储库、服务等),以便触发依赖项注入链。
也就是说,在控制器中使用具体类型(例如 DonorContext)有点违背了使用依赖注入的目的,因为您对它进行了硬编码。
Ninject will automatically call the Dispose method of objects implementing
IDisposable
(at least that's what happened when I tested it with the latest version). If this doesn't happen for you I suspect that the problem is that you never use thisDonorContext
anywhere in your application. So it never gets instantiated and never gets disposed. For example if you had a controller which takes this context as constructor argument:It should work. It would also work if you had a service layer that takes this context as constructor argument and then you use this service in the controller (with constructor injection). At the end of the day you must have a controller which takes some dependency which itself might be the DonorContext or some other dependency which itself depends on DonorContext (repository, service, ...) in order to trigger the dependency injection chain.
This being said working with a concrete type such as DonorContext in your controller kind of defeats the purpose of using Dependency Injection as you are hardcoding it.