如何使用 Windsor 将依赖项注入 ActionFilterAttributes [英] How do I use Windsor to inject dependencies into ActionFilterAttributes

查看:23
本文介绍了如何使用 Windsor 将依赖项注入 ActionFilterAttributes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看过NInject 可以做到AutoFac 可以做到我想弄清楚如何使用 Castle Windsor 将依赖项注入 MVC ActionFilters

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 with ctor 将 Type 作为参数 - 即像这样:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆