Our web application is built on the .NET Framework 4.6+. We're using WebForms, MVC 5.2, and Web API 2.
I'm in the process of trying to integrate Microsoft.Extensions.DependencyInjection and Microsoft.Extensions.Http into this solution so we can take advantage of the new HttpClientFactory that's in ASP.NET Core. We also want to start using DI in our MVC and API controllers.
It appears there are two ways this can be achieved:
- Write a custom ControllerActivator
- Write a custom DependencyResolver
Based on the reading I've done, it appears the ControllerActivator method is the old way of doing this, and the DependencyResolver is the current, preferred way of handling this. I've written code for both, and both methods appear to work.
Considering the DependencyResolver appears to be the preferred solution for DI now, I'd like to use it but I'm not sure if I'm handling scope object disposal correctly.
Here's how I'm configuring the DependencyResolvers in Global.asax:
Web.Mvc.DependencyResolver.SetResolver(New Mvc.DependencyInjection.DependencyResolver(serviceProvider))
GlobalConfiguration.Configuration.DependencyResolver = New Api.DependencyInjection.DependencyResolver(serviceProvider)
My System.Web.Http.Dependencies.IDependencyResolver implementation for Web API is:
public class DependencyResolver : IDependencyResolver
{
private IServiceProvider ServiceProvider { get; }
public DependencyResolver(IServiceProvider serviceProvider) => ServiceProvider = serviceProvider;
public IDependencyScope BeginScope() => new DependencyResolver(ServiceProvider.CreateScope().ServiceProvider);
public void Dispose() => (ServiceProvider as IDisposable)?.Dispose();
public object GetService(Type serviceType) => ServiceProvider.GetService(serviceType);
public IEnumerable<object> GetServices(Type serviceType) => ServiceProvider.GetServices(serviceType);
}
My System.Web.Mvc.IDependencyResolver implementation for MVC is:
public class DependencyResolver : IDependencyResolver
{
private IServiceProvider ServiceProvider { get; }
public DependencyResolver(IServiceProvider serviceProvider) => ServiceProvider = serviceProvider;
public object GetService(Type serviceType) => ServiceProvider.GetService(serviceType);
public IEnumerable<object> GetServices(Type serviceType) => ServiceProvider.GetServices(serviceType);
}
The System.Web.Http.Dependencies.IDependencyResolver
interface has Dispose()
, and it appears API requests do call my implementation's Dispose method. So that appears to be working (I think).
My concern is the System.Web.Mvc.IDependencyResolver
interface doesn't have Dispose()
, I'm not clear if these service objects are being properly disposed after a MVC request.
If anyone can provide some insight into this I'd really appreciate it. Don't want to roll this out and find out we're leaking memory.