Instatiate with Unity two objects of same interfac

2019-09-09 07:36发布

问题:

I have a case where I need to instantiate for the same interface two different implementation that are both used in the same class.

public AutoMapperRegisterFactory(IRegisterAutoMapper registerAutoMapper , IRegisterAutoMapper registerAutoMapperMobile)
{
   m_RegisterAutoMapper = registerAutoMapper;
}

How would I go about of telling unity that the first IRegisterAutoMapper should be of type RegisterAutoMapper and the second of type RegisterAutoMapperMobile ?

回答1:

You can do it with multiple named mappings for IRegisterAutoMapper combined with an InjectionConstructor telling Unity what specific mappings to use for each argument.

IUnityContainer container = new UnityContainer()
    .RegisterType<IRegisterAutoMapper, RegisterAutoMapper>() //default
    .RegisterType<IRegisterAutoMapper, MobileRegisterAutoMapper>("Mobile")
    .RegisterType<AutoMapperRegisterFactory>(
        new InjectionConstructor(
            typeof(IRegisterAutoMapper), 
            new ResolvedParameter<IRegisterAutoMapper>("Mobile")));