本文介绍了Spring.Net&安培;属性注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要依赖注入使用Spring.Net在ASP.NET MVC的属性,我的属性是这样的(注意这是所有伪code,我刚才输入)...

 公共类InjectedAttribute:ActionFilterAttribute
{
    私人IBusinessLogic businessLogic;    公共InjectedAttribute(IBusinessLogic businessLogic)
    {
        this.businessLogic = businessLogic;
    }    公共覆盖无效OnActionExecuting(ActionExecutedContext filterContext)
    {
        //做一些业务逻辑
        businessLogic.DoSomethingImportant();
    }
}

我使用一个控制器工厂创建还可与不同的业务逻辑对象注入的控制器。我越来越从IoC容器控制器这样的...

  ContextRegistry.GetContext()GetObject的(MyMVCController);

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

 <对象名称=MyMVCControllerTYPE =MyMVC.MyMVCController,MyMVC>
    <构造带参数的指数=0REF =businessLogic/>
< /对象>

有没有配置属性的注射的方法吗?我真的不希望把这个变成我的属性...

 公共类InjectedAttribute:ActionFilterAttribute
{
    私人IBusinessLogic businessLogic;    公共InjectedAttribute(IBusinessLogic businessLogic)
    {
        this.businessLogic = ContextRegistry.GetContext()GetObject的(businessLogic);
    }
    ....


解决方案

This defines controllers as singletons meaning that they will be reused among all requests which could be catastrophic. Ensure controllers are not defined as singletons:

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

Now, this being said let's go back to the main question about attributes.

Because you want constructor injection in your filters you can no longer decorate any controllers or actions with them as attribute values must be known at compile time. You need a mechanism to apply those filters at runtime to controllers/actions.

If you are using ASP.NET MVC 3 you could write a custom filter provider which will apply your action filter to desired controllers/actions by injecting dependencies into it.

If you are using an older version you could use a custom ControllerActionInvoker.

这篇关于Spring.Net&安培;属性注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:17