How to do dependency injection to Action Filter on ASP.NET Web API

南笙酒味 提交于 2019-12-03 05:41:47
AlexGad

You need to check your specific IOC implementation. IOC Containers such as NInject and Autofac have some type of filter injection by injecting public properties. Windsor I am unsure about, but here is a link that creates a wrapper which might help with Windsor: http://eagle081183.wordpress.com/2010/09/21/dependency-injection-with-asp-net-mvc-action-filters/ and another article directly addressing the issue with Windsor: http://weblogs.asp.net/psteele/archive/2009/11/04/using-windsor-to-inject-dependencies-into-asp-net-mvc-actionfilters.aspx.

For completeness with NInject and Autofac:

NInject:

Autofac:

**EDIT - additional option **

You should be able to do GlobalConfiguration.Configuration.DependencyResolver.GetService(...) from any filter regardless of the IOC container you are using.

Vladimir

For WebAPI and AutoFac you can use:

builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);

The documentation is here.

You can use the Ninject.Web.WebApi assembly (obviously using Ninject as the IoC) to make this work. I would suggest looking at the source and SampleApplication via https://github.com/ninject/Ninject.Web.WebApi to see how they are accomplishing Filter injection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!