2011-07-03 45 views
1

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

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"); 
    } 
    .... 

回答

2

我配置我的控制器,像这样通过在业务逻辑

这定义控制器作为单身意味着它们将在可能造成灾难性的所有请求中重用。确保控制器没有定义为单例:

<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

+0

它的MVC 1,所以我将无法使用自定义筛选器提供程序... – Gaz

+0

这工作很好,最佳答案:) – Gaz