views:

40

answers:

1

Hi!

I think my question is a long shot.

Lets say I have an attribute:

public sealed class MyCustomAttribute: ActionFilterAttribute

Used on a class method

    [MyCustomAttribute]
    public virtual ActionResult Options(FormCollection collection)

Now, I need to add a contructor's parameter

    public MyCustomAttribute(IMyDependentObject dependentObject)
    {           
              (...)
    }

(You propably notice that it's some Asp.NET MCV code)

I would like to use DI to create this attribute. Asp.NET MVC code automatically create it and I don't know how/where I could write code to use Castle istead.

Any ideas?

+1  A: 

As far a I konw castle does not support injection of existing objects, which makes it impossible to inject attributes as their construction is not under your control. Other IoC containers such as Ninject support injection of existing objects. They inject properties of your attribut filter. See http://github.com/ninject/ninject.web.mvc for an extension that exactly does what you need.


What you can do if you want to stay on castle is to inject your own ControllerActionInvoker derived from ControllerActionInvoker (AsyncControllerActionInvoker in case of async controller) into all controllers. In your own invoker you override GetFilters. Additionally to the Filters returned by the base you add FilterInfos that are created by castle.

The decision which filters infos are created and added can be achieved with various strategies e.g.:

  • Add an own custom attribute that contains the information e.g. name of a binding
  • A configuration file/database

May you consider switching to MVC3 this makes all a bit easier. As you can register your own FilterProvider which makes all much easier. In this FilterProvider you have to decide which filter info you want to add. See again the two strategies above. See http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html for information about MVC3 and filters.

Remo Gloor
Thanks for the MVC3 tip. I'll look at it and give it a try
vIceBerg