问题
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