Created
November 7, 2012 22:35
-
-
Save blair55/4034984 to your computer and use it in GitHub Desktop.
WebAPI ActionFilter Dependency Injection with StructureMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Web.Http.Controllers; | |
using System.Web.Http.Filters; | |
using Raven.Client; | |
namespace MyWebApi.Attributes | |
{ | |
public class AggressivelyCacheAttribute : ActionFilterAttribute | |
{ | |
public IDocumentStore DocumentStore { get; set; } | |
public override void OnActionExecuting(HttpActionContext actionContext) | |
{ | |
base.OnActionExecuting(actionContext); | |
DocumentStore.AggressivelyCacheFor(TimeSpan.FromMinutes(10)); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class IoC | |
{ | |
public static IContainer Initialize() | |
{ | |
var documentStore = new DocumentStore { ConnectionStringName = "RavenDB" }; | |
documentStore.Initialize(); | |
ObjectFactory.Initialize(cfg => | |
{ | |
cfg.For<IFilterProvider>().Use<SmFilterProvider>(); | |
cfg.For<IDocumentStore>().Use(documentStore); | |
cfg.FillAllPropertiesOfType<IDocumentStore>(); | |
}); | |
return ObjectFactory.Container; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SmFilterProvider : ActionDescriptorFilterProvider, IFilterProvider | |
{ | |
private readonly IContainer _container; | |
public SmFilterProvider(IContainer container) | |
{ | |
_container = container; | |
} | |
public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor) | |
{ | |
var filters = base.GetFilters(configuration, actionDescriptor); | |
foreach (var filter in filters) | |
{ | |
_container.BuildUp(filter.Instance); | |
} | |
return filters; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It this working? I'm getting this error:
Bi-directional dependency relationship detected! Check the StructureMap stacktrace below:
1.) new StructureMapFilterProvider(Default of IContainer, Enumerable of System.Web.Http.Filters.IFilterProvider with all registered instances)
2.) StructureMapFilterProvider
3.) Instance of System.Web.Http.Filters.IFilterProvider (StructureMapFilterProvider)
4.) Container.GetAllInstances(System.Web.Http.Filters.IFilterProvider)