如何使用温莎依赖注入ActionFilterAttributes

如何使用温莎依赖注入ActionFilterAttributes

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

问题描述

我们已经看到如何<一个href=\"http://$c$cclimber.net.nz/archive/2009/02/10/how-to-use-ninject-to-inject-dependencies-into-asp.net-mvc.aspx\">NInject能做到这一点和AutoFac能做到这一点我试图弄清楚如何使用注入温莎城堡的依赖到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的辅助类来解决从构造code这样的依赖关系:

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与男星采取类型作为参数 - 即是这样的:

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! :-)

这篇关于如何使用温莎依赖注入ActionFilterAttributes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:01