Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting dependency into CustomAttribute using Castle Windsor

In my ASP.Net MVC application I have implemented a Custom ActionFilter to Authorize users.

I use CastleWindsor to provide dependency injection into all of the controllers as follows:

  protected virtual IWindsorContainer InitializeServiceLocator()
    {
        IWindsorContainer container = new WindsorContainer();
        ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));

        container.RegisterControllers(typeof(HomeController).Assembly);
        ComponentRegistrar.AddComponentsTo(container);

        ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));

        return container;
    }

Within my CustomAttribute, I need a dependency that is used by all of my controllers, however I am unable to user Constructor based injection in an attribute.

So what's the cleanest way out here? How can I provide the dependency?

like image 780
BonyT Avatar asked May 25 '11 15:05

BonyT


2 Answers

OK - this seems to be a duplicate of Database injection into a validation attribute with ASP MVC and Castle Windsor which has been answered.

Also How do I use Windsor to inject dependencies into ActionFilterAttributes.

Having read through the above, and the referenced articles - the key one for me is http://weblogs.asp.net/psteele/archive/2009/11/04/using-windsor-to-inject-dependencies-into-asp-net-mvc-actionfilters.aspx for anyone else who is interested.

like image 67
BonyT Avatar answered Nov 02 '22 04:11

BonyT


You can't. Attributes are metadata. Putting behaviour into them is wrong. Putting dependencies is even worse.

Use your attribute as marker to denote objects to which you want to apply the behavior and implement the behavior elsewhere.

In MVC elsewhere usually means a custom action invoker that uses data from the attribute to provide the behavior you need.

like image 1
Krzysztof Kozmic Avatar answered Nov 02 '22 04:11

Krzysztof Kozmic