【问题标题】:Spring.Net & Attribute InjectionSpring.Net & 属性注入
【发布时间】:2011-07-03 10:02:30
【问题描述】:

我想使用 Spring.Net 在 ASP.NET MVC 中依赖注入一个属性,我的属性是这样的(注意这是我刚刚输入的所有伪代码)...

public class InjectedAttribute : ActionFilterAttribute
{
    private IBusinessLogic businessLogic;

    public InjectedAttribute(IBusinessLogic businessLogic)
    {
        this.businessLogic = businessLogic;
    }

    public override void OnActionExecuting(ActionExecutedContext filterContext)
    {
        // do something with the business logic
        businessLogic.DoSomethingImportant();
    }
}

我正在使用控制器工厂来创建控制器,这些控制器也注入了各种业务逻辑对象。我正在像这样从 IoC 容器中获取控制器...

ContextRegistry.GetContext().GetObject("MyMVCController");

我正在配置我的控制器,就像这样传递业务逻辑

<object name="MyMVCController" type="MyMVC.MyMVCController, MyMVC">
    <constructor-arg index="0" ref="businessLogic" />
</object>

有没有办法配置属性的注入?我真的不想把它放到我的属性中......

public class InjectedAttribute : ActionFilterAttribute
{
    private IBusinessLogic businessLogic;

    public InjectedAttribute(IBusinessLogic businessLogic)
    {
        this.businessLogic = ContextRegistry.GetContext().GetObject("businessLogic");
    }
    ....

【问题讨论】:

    标签: asp.net-mvc dependency-injection spring.net


    【解决方案1】:

    我正在配置我的控制器,就像这样传递业务逻辑

    这将控制器定义为单例,这意味着它们将在所有可能是灾难性的请求中重复使用。确保控制器未定义为单例:

    <object name="AnotherMovieFinder" type="MyMVC.MyMVCController, MyMVC" singleton="false">
        <constructor-arg index="0" ref="businessLogic" />
    </object>
    

    现在,话虽如此,让我们回到关于属性的主要问题。

    因为您希望在过滤器中注入构造函数,所以您不能再用它们装饰任何控制器或操作,因为属性值必须在编译时知道。您需要一种机制来在运行时将这些过滤器应用于控制器/动作。

    如果您使用的是 ASP.NET MVC 3,您可以编写一个 custom filter provider,通过向其中注入依赖项,将您的操作过滤器应用于所需的控制器/操作。

    如果您使用的是旧版本,您可以使用custom ControllerActionInvoker。

    【讨论】:

      猜你喜欢
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      相关资源
      最近更新 更多