asp.NET MVC 2 ActionFilter上的依赖注入/属性注入:帮助!

mor*_*pdx 1 dependency-injection asp.net-mvc-2

我一直试图围绕这个类似问题发布的主题:

是否可以在ASP.NET MVC FilterAttribute上使用依赖注入/ IoC?

但是,我只是没有到达任何地方.更不用说,所有解决方案似乎都依赖于我无法使用的其他库(MvcContrib,Unity).

任何人都可以将一些代码拼凑在一起来解释如何使这个属性注入工作?或者,如果有另一种方法可以实现这一目标?

非常感谢!

相关代码1:控制器

namespace TxRP.Controllers
{
    [GetMasterPageData] 
    public class BaseController : Controller
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

相关代码2:ActionFilter

public class GetMasterPageData : ActionFilterAttribute
{
    private IEmployee emp; //<--Need to inject!
    private ICache cache;  //<--Need to inject!

    /// <summary>
    /// ActionFilter attribute which inserts the user name, access level and any error/warning messages to the MasterPage
    /// Session variables which are consumed primarily by the LogOnUserControl.
    /// The MasterPage will display any warning or error messages.
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
                 //Code
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ann 5

不能将DI与属性一起使用,因为它们被静态编译到您的类中,因此无法注入任何内容.有些人可能会告诉你,你可以使用一种静态工厂来获取你的依赖关系,但这不是依赖注入 - 那就是服务位置 - 这是一种反模式.

但是,如果放弃属性的想法,可以将DI与动作过滤器结合起来,但不是特别容易.您需要创建一个自定义IActionInvoker,尽管最简单的方法是从ControllerActionInvoker派生并覆盖其GetFilters方法.这是一篇博客文章,解释了如何为错误处理做到这一点 - 你应该能够从中推断出来.

当你厌倦了这样做时,我会建议你转而从装饰师和其他设计模式中解决交叉问题.通过这种方式,您可以独立于约束技术来实现您的横切关注点.