Unity dependency injection in an ASP MVC 5.0 RoleP

2019-08-28 06:05发布

问题:

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)