Structuremap - multiple interface implementations
Asked Answered
I

1

8

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 in 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!

Immunize answered 23/6, 2011 at 19:3 Comment(0)
W
10

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);
Whereto answered 23/6, 2011 at 21:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.