I’m working on a .net webAPI project where we are using dependency injection (StructureMap I believe) to provide our controllers instances of per-session Data Access Objects. This part works great.
What I now need to do is provide an instance of AuthorizationFilterAttribute with a DataAccessObject.
The AuthorizationFilterAttribute is used via an annotation. For example:
[ApiKeyAuthorization]
public DataModel ControllerAction(int id) { }
That will ensure that before the controller gets to run, authorization is checked.
What I need is for that ApiKeyAuthorization object to be created with reference to my shared-per-session Database Access Object.
Is there an easy way to make that happen?
There are several similar questions on SO about dependency injection to Action Filters. Here are few:
Ninject and MVC3: Dependency injection to action filters
How to use dependency injection with an attribute?
Injecting dependencies into ASP.NET MVC 3 action filters. What's wrong with this approach?
Jimmy Bogart’s blog post (linked from one of the answers): http://lostechies.com/jimmybogard/2010/05/03/dependency-injection-in-asp-net-mvc-filters/
Another StructureMap based solution: http://www.thecodinghumanist.com/blog/archives/2011/1/27/structuremap-action-filters-and-dependency-injection-in-asp-net-mvc-3
An interesting solution for allowing constructor based injection for action filters: http://iridescence.no/post/Constructor-Injection-for-ASPNET-MVC-Action-Filters.aspx
Hope it will take you on the right track.