Unity Container trying to resolve non registered t

2019-08-11 12:10发布

问题:

I've inherited an existing ASP.Net MVC project that makes use of a Unity DI container. All of its registrations are defined in web.config.

When a new service / class is introduced into the project, I create it along with an Interface, and then update the config file to handle the registration. For example :

 

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <assembly name="UnityDi.Contracts" />
    <assembly name="UnityDi.Domain" />
    <assembly name="UnityDi.Services" />
    <assembly name="UnityDi.Repositories" />
    <namespace name="UnityDi.Contracts" />
    <namespace name="UnityDi.Domain" />
    <namespace name="UnityDi.Services" />
    <namespace name="UnityDi.Repositories" />
    <container>
        <register type="Foo.Worker.Interfaces.IIndividualWorker, Foo.Worker" mapTo="Foo.Worker.Workers.IndividualWorker, Foo.Worker"></register>
    </container>
</unity>

When IIndividualWorker is required in a class or controller , I add it with the Dependency attribute :

[Dependency]
public IIndividualWorker IndividualWorker { get; set; }

So far, this works fine......

I've hit a problem now that I don't understand, and I admit my Unity knowledge isn't the deepest.

I created a new MVC Web Application, it will utilize the same back-end tiers as the first application, shown above. I have configured the Web.Config in the same way, and all the references are in place. The problem I get is that the new web application utilizes ASP.Net Identity for it's security mechanism (the previous application had Simple Membership).

On registering a new User, using the standard ASP.Net MVC Authentication templates, I get the error "The current type, Microsoft.AspNet.Identity.IUserStore`1[Foo.Web2.Models.ApplicationUser], is an interface and cannot be constructed. Are you missing a type mapping?"

It seems that Unity is trying to handle the parameter of the ApplicationUserManager class

public ApplicationUserManager(IUserStore<ApplicationUser> store)

Is there a way around this? Can I get Unity to leave this (and presumably other templated code) alone, and only try to resolve those I've defined in my .Config?

Thanks,

回答1:

In the end, I explicitly added the registration of the IUserStore

container.RegisterType(typeof(IUserStore<ApplicationUser>), typeof(UserStore<ApplicationUser>));

What threw me was that the addition of Unity seems to affect many interfaces throughout the codebase that previously worked. Any more errors of this nature I'll be sure to explicitly register the offending interface.

I still suspect there must be options to keep Unity limited to only the registrations provided, can any Unity experts advise?