问题
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