Ninject: Handling Object Lifetime and Dependency Injection
Question 1: DbContext Cleanup
When using Ninject, you don't need to worry about manually disposing of DbContext instances. Ninject automatically disposes any disposable object that is not bound with the InTransientScope(). Since most likely you're using InParentScope() or other scopes, Ninject will handle the disposal when the corresponding scope is collected by the garbage collector.
Question 2: Avoiding Injected DbContext in Base Controller
It's generally recommended to avoid using base classes for MVC Controllers. They tend to violate the Single Responsibility Principle and lead to god objects. Instead, consider using globally registered filters to handle cross-cutting concerns.
Example:
Suppose you want to set common ViewBag properties based on the current user. You could create an IAuthorizationFilter like this:
public class CurrentUserProfileFilter : IAuthorizationFilter { private readonly MyDbContext context; public CurrentUserProfileFilter(MyDbContext context) { this.context = context; } public void OnAuthorization(AuthorizationContext filterContext) { // Set ViewBag properties based on current user information from DbContext } }
Then, register the filter globally in your FilterConfig:
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { FilterProviders.Providers.Insert(0, new GlobalFilterProvider(DependencyResolver.Current)); } }
This will automatically set the ViewBag properties on every request without requiring you to inject MyDbContext into your controllers.
Question 3: Lazy DB Context Instantiation
By default, Ninject creates objects eagerly, but it's possible to make an object bound by Ninject lazy (created only when first requested).
However, this is not recommended for DbContext since it has a substantial initialization overhead, so it would be pointless to defer its creation. Plus, a DbContext should be disposed when it's finished with, and its lifetime should be controlled accordingly.
The above is the detailed content of How Does Ninject Manage DbContext Lifetime and Dependency Injection?. For more information, please follow other related articles on the PHP Chinese website!