c# - How can I inject dependencies into a System.Web.Http.AuthorizeAttribute subclass? -
i'm working on asp.net web application uses web api 2 , unity. we've decorated our controllers/controller methods subclass of built-in system.web.http.authorizeattribute apply authorization our various rest endpoints exposed web api.
we able inject dependencies attribute using unity. i've done quite bit of searching, examples different enough use case not useful.
how go injecting dependencies system.web.http.authorizeattribute subclass using unity?
i've tried creating custom filterprovider calls unity's buildup
method on attribute instance, i'm not sure base class should extending or interface should implementing.
you have implement ifilterprovider. if extend actiondescriptorfilterprovider can call base.getfilters filters specified both @ controller , action level.
public class unityfilterprovider : actiondescriptorfilterprovider, ifilterprovider { private readonly iunitycontainer _container; public unityfilterprovider(iunitycontainer container) { _container = container; } public new ienumerable<filterinfo> getfilters(httpconfiguration configuration, httpactiondescriptor actiondescriptor) { var attributes = base.getfilters(configuration, actiondescriptor).tolist(); foreach (var attr in attributes) { _container.buildup(attr.instance.gettype(), attr.instance); } return attributes; } }
you have register infrastructure used instead of default one:
//register filter injector var providers = config.services.getfilterproviders().tolist(); var defaultprovider = providers.single(i => actiondescriptorfilterprovider); config.services.remove(typeof(ifilterprovider), defaultprovider); config.services.add(typeof(ifilterprovider), new unityfilterprovider(unityconfig.container));
Comments
Post a Comment