Spring.Net & Attribute Injection

2019-08-11 05:52发布

问题:

I want to dependency inject an attribute in ASP.NET MVC using Spring.Net, my attribute is something like this (note this is all pseudo code I've just typed in)...

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();
    }
}

I'm using a controller factory to create the Controllers which are also injected with various business logic objects. I'm getting the controllers from the IoC container like this...

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

I'm configuring my Controllers like so passing in the business logic

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

Is there a way to configure the injection of the attributes? I don't really want to put this into my attributes...

public class InjectedAttribute : ActionFilterAttribute
{
    private IBusinessLogic businessLogic;

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

回答1:

I'm configuring my Controllers like so passing in the business logic

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.