How to register multiple types that implement the same interface

大兔子大兔子 提交于 2019-12-06 03:34:27

This is how I do it:

        var container = new UnityContainer().RegisterType<IAmImplementedMoreThanOnce, Implementation1>("Implementation1")
                                            .RegisterType<IAmImplementedMoreThanOnce, Implementation2>("Implementation2")
                                            .RegisterType<IHaveDependencies1, WithDependenciesImplementation1>(new InjectionConstructor(new ResolvedParameter<IAmImplementedMoreThanOnce>("Implementation1")))
                                            .RegisterType<IHaveDependencies2, WithDependenciesImplementation2>(new InjectionConstructor(new ResolvedParameter<IAmImplementedMoreThanOnce>("Implementation2")));

you should register whichever instance of type you want. If you register both types for same interface you get the only one. One interface for each type, or you provide input parameter for the type you register. It acts like container, you put your stuff in and get it back anytime you want with the correct key.

Either you would create another two interface for your two types which are derived from parent interface and register these two interface for your two types, or use input parameters.

e.g.

you have

ClassA : IClass and ClassB : IClass right?

So, it'll be like; ClassA : IClassA , ClassB : IClassB and IClassA : IClass , IClassB: IClass and register IClassA for ClassA and IClassB for ClassB.

input parameters

RegisterType IClass, ClassA>("TypeA");
RegisterType IClass, ClassB>("TypeB");

Resolve IClass>("TypeA");
Resolve IClass>("TypeB");

make sense?

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