Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 999
Jill Avatar asked Jun 23 '11 19:06

Jill


1 Answers

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);
like image 114
Bassetassen Avatar answered Nov 16 '22 00:11

Bassetassen