How to register multiple types that implement the same interface

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 10:49:28

问题


I have a single interface and this is being used by 2 classes. I am using unity configuration to identify the instance based on the interface.

Now I want to know how should i register these types so that i can call the appropriate implementation based on the single interface itself.


回答1:


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")));



回答2:


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?



来源:https://stackoverflow.com/questions/6109404/how-to-register-multiple-types-that-implement-the-same-interface

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