开发者

Structuremap - multiple interface implementations

I am totally new to Structuremap and am confused on how to wire an interface that has multiple implementations.

Lets say I have Controller1 and Controller2. I have Interface1 that is implemented by two separate classes, Class1ForInterface1 and Class2ForInterface1. In Controller1 I want Class1ForInterFace1 injected and i开发者_运维知识库n Controller2 I want Class2ForInterface1 injected.

How do I wire this with structuremap? It seems that I can only have one mapping of Interface to concrete type?

Thanks!


It is possible to have several classes implementing the same interface with structuremap.

If you name your mappings, you can retrive them with that name later.

For<MyInterface>().Add<Class1ForMyInterface>().Named("Class1");
For<MyInterface>().Add<Class2ForMyInterface>().Named("Class2");

If you then want your Class1ForMyInterface then you can call

container.GetInstance<MyInterface>("Class1");

There is also a couple of ways to map all this in you container aswell

For<IController>().Add<Controller1>().Ctor<MyInterface>().Is(i => i.GetInstance<MyInterface>("Class1"));

Or if you keep the smartinsatance that is returned when you register a type, you can use it in the mapping.

var class1 = For<MyInterface>().Add<Class1ForMyInterface>().Named("Class1");
For<IController>().Add<Controller1>().Ctor<MyInterface>().Is(class1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜