Skip to content
wald-tq edited this page Jul 17, 2015 · 2 revisions

The MVC framework itsself caches filters. Therefore the filter is not allowed to take any dependency with a scope that has a lifetime which is shorter than the filter. In other words it is only allowed to reference objects in the following scopes:

  • Singleton
  • Transient
  • Call Scope (from the Named Scope extension)
  • Parent Scope (from the Named Scope extension)
  • Custom Scopes which life longer than the filter

If you need a dependency in another scope e.g. InRequestScope that you must not reference it directly. In this case you must inject a Factory (e.g. with the Factory extension) and create the object during the evaluation of the filter.

public interface IMyObjectInRequestScopeFactroy
{
    IMyObjectInRequestScope CreateMyObjectInRequestScope();
}

public class MyFilter : IActionFilter
{
    IMyObjectInRequestScopeFactory factory;

    public MyFilter (IMyObjectInRequestScopeFactory factory)
    {
        this.factory = factory;
    }
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        this.factory.CreateMyObjectInRequestScope()
    }
}