如何在ASP.NET Web API上对Action Filter执行依赖项注入
我真的陷入了将dependency injection到web api的动作filter中的方法。 我有一个这样的动作filter:
public class AuthorizationAttribute : ActionFilterAttribute { public IApiKeyRepository Repository { get; set; } private Guid GetApiKey(string customerKey) { return Repository.GetApiKey(customerKey); } public override void OnActionExecuting(HttpActionContext actionContext) { } }
我想通过使用Windsor在属性Repository上进行属性注入(但是使用哪个IoC容器并不重要)
我确实想要自定义FilterProvider,但它没有为我工作,有没有人有解决方案或运行代码? 非常感谢
您需要检查您的具体IOC实施。 IOC容器(如NInject和Autofac)通过注入公共属性来进行某种类型的filter注入。 Windsor我不确定,但是这里有一个链接可以创建一个可以帮助Windsor的包装器: http : //eagle081183.wordpress.com/2010/09/21/dependency-injection-with-asp-net-mvc-action -filters /和另一篇直接解决Windsor问题的文章: http : //weblogs.asp.net/psteele/archive/2009/11/04/using-windsor-to-inject-dependencies-into-asp-net-mvc -actionfilters.aspx 。
为了完整性,使用NInject和Autofac:
NInject:
- http://codeclimber.net.nz/archive/2009/02/10/how-to-use-ninject-to-inject-dependencies-into-asp.net-mvc.aspx
- 动作filter中的Ninject
Autofac:
- ASP.NET MVC 3,动作filter和Autofacdependency injection
**编辑 – 附加选项**
无论您使用何种IOC容器,您都应该可以从任何filter执行GlobalConfiguration.Configuration.DependencyResolver.GetService(...)
。
对于WebAPI和AutoFac,您可以使用:
builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);
文档在这里 。
您可以使用Ninject.Web.WebApi程序集(显然使用Ninject作为IoC)来完成这项工作。 我建议通过https://github.com/ninject/Ninject.Web.WebApi查看源代码和SampleApplication,看看它们是如何完成Filter注入的。