Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorization and Windsor

I'm trying to implement my custom authorize attribute like:

 public class MyCustomAuth : AuthorizeAttribute
{
    private readonly IUserService _userService;

    public MyCustomAuth(IUserService userService)
    {
        _userService= userService;
    }
... continued
 }

I am using Castle Windsor for automatically resolve the dependency.

When I try to use it as an attribute of an action method obviously I am asked to pass the parameter or I need to have a parameter-less constructor that should resolve in some way it's dependency.

I tried to inject the dependency with a property but Windsor is not injecting it.

The only option I see now would be to instantiate manually the concrete object dependency loosing the benefit of Windsor.

How would you solve this problem?

like image 651
Ronnie Avatar asked Nov 06 '09 17:11

Ronnie


2 Answers

You cannot use DI with attributes - they're metadata;

public class MyCustomAuth : AuthorizeAttribute
{
    public void OnAuthorization(...)
    {
         IUserService userService = ServiceLocator.Current.GetInstance<IUserService>();
    }
}

Learn about Windsor/ServiceLocator here.

See similar question here.

like image 165
queen3 Avatar answered Nov 05 '22 07:11

queen3


You can use a custom ControllerActionInvoker and inject property dependencies (you can't do constructor injection because the framework handles instantiation of attributes). You can see a blog post I just did on this technique.

like image 3
PatrickSteele Avatar answered Nov 05 '22 07:11

PatrickSteele