问题描述
看过如何和 AutoFac可以做到这一点我试图找出如何使用Castle Windsor注入到MVC ActionFilter中的依赖关系
Having seen how NInject can do it and AutoFac can do it I'm trying to figure out how to inject dependencies into MVC ActionFilters using Castle Windsor
目前,我使用一个丑陋的静态IoC帮助器类来解决构造函数代码中的依赖关系,如下所示:
At the moment I'm using an ugly static IoC helper class to resolve dependencies from the constructor code like this:
public class MyFilterAttribute : ActionFilterAttribute
{
private readonly IUserRepository _userRepository;
public MyFilterAttribute() : this(IoC.Resolve<IUserRepository>()) { }
public MyFilterAttribute(IUserRepository userRepository)
{
_userRepository = userRepository;
}
}
我想删除静态反模式IoC的东西从我的过滤器。
I'd love to remove that static antipattern IoC thing from my filters.
任何提示,我将如何去做与温莎城堡?
Any hints to as how I would go about doing that with Castle Windsor?
不,改变DI框架是不是一个选项。
And no, changing DI framework is not an option.
推荐答案
创建一个通用属性:MyFilterAttribute与ctor取一个Type作为参数 - ie如下所示:
Make a generic attribute: MyFilterAttribute with ctor taking a Type as argument - i.e. something like this:
public class MyFilterAttribute : ActionFilterAttribute {
public MyFilterAttribute(Type serviceType) {
this.serviceType = serviceType;
}
public override void OnActionExecuting(FilterExecutingContext c) {
Container.Resolve<IFilterService>(serviceType).OnActionExecuting(c);
// alternatively swap c with some context defined by you
}
// (...) action executed implemented analogously
public Type ServiceType { get { return serviceType; } }
public IWindsorContainer Container { set; get; }
}
然后使用与您所指的两个文章相同的方法,命令控制如何调用操作,并手动将WindsorContainer注入属性。
Then use the same approach as the two articles you are referring to, in order to take control of how actions are invoked, and do a manual injection of your WindsorContainer into the attribute.
用法:
[MyFilter(typeof(IMyFilterService) )]
Usage: [MyFilter(typeof(IMyFilterService))]
您的实际过滤器将在一个实现IMyFilterService的类中,而后者又应该实现IFilterService,可以看起来像这样:
Your actual filter will then be in a class implementing IMyFilterService which in turn should implement IFilterService which could look something like this:
public interface IFilterService {
void ActionExecuting(ActionExecutingContext c);
void ActionExecuted(ActionExecutedContext c);
}
这样你的过滤器甚至不会被绑定到ASP.NET MVC,你的属性只是一个元数据 - 它实际上应该是这样的! : - )
This way your filter will not even be tied to ASP.NET MVC, and your attribute is merely a piece of metadata - the way it is actually supposed to be! :-)
这篇关于如何使用Windsor将依赖项注入到ActionFilterAttributes中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!