Using Spring.Net to inject dependencies into ASP.NET MVC ActionFilters

百般思念 提交于 2019-12-11 02:25:06

问题


I'm using MvcContrib to do my Spring.Net ASP.Net MVC controller dependency injection. My dependencies are not being injected into my CustomAttribute action filter. How to I get my dependencies into it?

Say you have an ActionFilter that looks like so:

public class CustomAttribute : ActionFilterAttribute, ICustomAttribute
{
    private IAwesomeService awesomeService;

    public CustomAttribute(){}

    public CustomAttribute(IAwesomeService awesomeService)
    {
          this.awesomeService= awesomeService;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
         //Do some work
    }
}

With a Spring.Net configuration section that looks like so:

<object id="CustomAttribute " type="Assembly.CustomAttribute , Assembly" singleton="false">
    <constructor-arg ref="AwesomeService"/>
</object>

And you use the Attribute like so:

[Custom]
public FooController : Controller
{
    //Do some work
}

回答1:


The tough part here is that ActionFilters seem to get instantiated new with each request and in a context that is outside of where Spring is aware. I handled the same situations using the Spring "ContextRegistry" class in my ActionFilter constructor. Unfortunately it introduces Spring specific API usage into your code, which is a good practice to avoid, if possible.

Here's what my constructor looks like:

public MyAttribute()
{
    CustomHelper = ContextRegistry.GetContext().GetObject("CustomHelper") as IConfigHelper;
}

Keep in mind that if you are loading multiple Spring contexts, you will need to specify which context you want in the GetContext(...) method.



来源:https://stackoverflow.com/questions/1830376/using-spring-net-to-inject-dependencies-into-asp-net-mvc-actionfilters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!