Unity dependency injection in an ASP MVC 5.0 RoleProvider defined in configuration

筅森魡賤 提交于 2019-12-25 02:09:38

问题


I'm trying to implement a role provider using a separate EF repository class, as an injectable dependency, to access my roles store. My problem is that the role provider is defined in configuration (web.config) and therefore is not instantiated via the Unity DI container. I haven't been able to find a way to either shift the configuration to code or get hold of the role provider after it's built to call container.BuildUP() on it. Any suggestions would be appreciated.


回答1:


I think that my question's solution is fairly well covered here:

Property injection in custom membership provider using Castle

If I'd searched on MembershipProvider instead of RoleProvider probably would have found it the first time through.

Just to summarize my solution, the link lead me to the Common Service Locator library at codeplex.

It and the Unity adapter for it are included in the Nuget package for Unity 3. So I already had it.

I added one line to the end of the Compose() method of my CompositionRoot class:

var locator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => locator);

And I can now access the locator/container thru the static ServiceLocator class in the constructor of my RoleProvider:

    public IAuthorizationManager Manager {get; set;}

    public MyRoleProvider()
    {
        var locator = ServiceLocator.Current;
        Manager = locator.GetInstance<IAuthorizationManager>();
    }

(Of course, you need 'using' statements for Microsoft.Practices.ServiceLocation)



来源:https://stackoverflow.com/questions/22331355/unity-dependency-injection-in-an-asp-mvc-5-0-roleprovider-defined-in-configurati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!