3
votes

In order to flush changes to RavenDB in ASP.NET WebApi I created the following Action Filter:

public class RavenDbUnitOfWorkAttribute : ActionFilterAttribute
{
    public Func<IDocumentSession> SessionFactory { get; set; }
    
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        var session = SessionFactory.Invoke();
       
        if (session != null && actionExecutedContext.Exception == null)
        {
            session.SaveChanges();
        }
        
        base.OnActionExecuted(actionExecutedContext);
    }
}

To inject the IDocumentSession I created a custom IFilterProvider that loops through each filter and sets any dependencies using setter injection (StructureMap).

I would like to know how instances of IFilterProvider are scoped. Reading this article it appears Controllers are created per request.

Currently I'm explicitly scoping the IDocumentSession per request using StructureMap. The question is, if I instead rely on the IDependencyScope (that uses a nested container) would the same instance of IDocumentSession be injected into my Action Filter?

[Update]

Testing further it would seem that Action Filters do not use the same dependency scope as a Controller. I'd prefer not to have the code for flushing the session in my Controller however.

1
I don't have an asnwer, but this article talks about filters and DI bradwilson.typepad.com/blog/2010/07/… - suing
@suing this is referring to DI in MVC. My question is referring to DI in ASP.NET WebApi. The two are quite different. - Ben Foster

1 Answers

9
votes

As you practicly answered your own question in JabbR, using GetDependencyScope extension method for the HttpRequestMessage should solve your problem:

var session = Request.GetDependencyScope().GetService(typeof(IDocumentSession));