Search code examples
c#.netasp.net-web-apidependency-injectionunity-container

Filters and FilterProvider with Dependency Injection; Manage Per-request?


I have been experimenting with Unity and a customer Filter / FilterProvider. My concern is that the classes are never disposed. Here is a code example i started with:

//FilterProvider
public class CustomFilterProvider: IFilterProvider
    {


        public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
        {

            if (actionDescriptor.GetCustomAttributes<CustomAuthorizeAttribute>().Any())
            {
                var filter = UnityinstanceLocator.GetConfiguredContainer().Resolve<CustomAuthorize>();
                yield return new FilterInfo(filter, FilterScope.Global);
            }
        }
    }

//Filter
public class CustomAuthorizeFilter: IAuthorizationFilter
    {
        private readonly IFakeService _fakeService;

        public CustomAuthorizeFilter(IFakeService fakeService)
        {
            _fakeService = fakeService;
        }


        public bool AllowMultiple { get; }

        public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken,
            Func<Task<HttpResponseMessage>> continuation)
        {
           ...Do Some stuff
        }     
    }

 //Attribute
 public class CustomAuthorizeAttribute : Attribute
    {

    }

My IFakeService implements IDisposable. I set this up as a test. My unity registration for the IFakeService makes use of the HierarchicalLifetimeManager. I never see it being disposed when it is inside a filter. Injecting the IFakeService into the controller works as expected.

The startup for the filter provider looks like this (I am using OWIN):

var config = new HttpConfiguration {DependencyResolver = new UnityDependencyResolver(UnityinstanceLocator.GetConfiguredContainer())};
config.Services.Add(typeof(IFilterProvider), new ComceptFilterProvider());

I suppose I could go old school and wrap my disposable class in a using statement inside the ExecuteAuthorizationFilterAsync method and avoid Dependency Injection all together. Is there a better solution to this if I were to stay with Unity?


Solution

  • In WebApi framework filters are cached. So they are singletons and reused across requests. Instance of your CustomAuthorizeFilter never be disposed during lifetime of application and keeps reference to IFakeService.