Home >Backend Development >C++ >Ninject and DbContext: Ensuring Proper Disposal and Optimizing Instance Creation?
With the recent steps taken to incorporate Ninject into your MVC application and introduce DbContext into your controllers' constructors, certain questions naturally arise:
Does Ninject guarantee the cleanup and timely disposal of my DbContext instances?
As outlined in this response:
Per CLR documentation, the creator of a Disposable object is responsible for calling Dispose, which in this case is Ninject. Hence, explicit calls to Dispose are discouraged.
Ninject disposes Disposable objects within any scope other than InTransientScope() as soon as the GC collects the scope object to which they are tied. Therefore, all Disposable objects should be bound using a scope that is not InTransientScope().
Is it feasible to eliminate the requirement to include the DbContext argument in each controller?
Avoid using a shared base class for MVC controllers altogether. Class inheritance fosters tight coupling and hampers maintainability. Additionally, it tends to create "god objects" that necessitate further dependencies for each controller.
Alternatively, consider utilizing globally registered filters to handle cross-cutting concerns. You can design specific filters for distinct logical components, adhering to the Single Responsibility Principle, which would be violated by a shared base class. By registering them globally, you can employ constructor injection and even create attributes (without behavior) for conditional application at the controller and/or action level.
How can I optimize the creation of DbContext instances?
Refer to the following question for insights: [One DbContext per web request... why?](https://stackoverflow.com/questions/9155198/one-dbcontext-per-web-request-why)
The above is the detailed content of Ninject and DbContext: Ensuring Proper Disposal and Optimizing Instance Creation?. For more information, please follow other related articles on the PHP Chinese website!