views:

189

answers:

2

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:

And you use the Attribute like so: [Custom] public FooController : Controller { //Do some work }

A: 

So, could you solve this issue? Were you able to inject your dependencies into the Custom attribute?

Regards!

Mauricio
A: 

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.

brow-cow