How to map the same interface to different ConcreteClasses with StructureMap?

When Controller1 is created, I want IService to be mapped to ConcreteService1 and IPageService to ConcretePageService1

And when Controller2 is created, I want IService to be mapped to ConcreteService2 and IPageService to ConcretePageService2

How can I initialize an ObjectFactory so that the above works?

While I initialized ObjectFactory as follows:

ObjectFactory.Initialize(x => { x.For<IService>().Use<ConcreteService1>(); x.For<IPageService>().Use<ConcretePageService1>(); }); 

But it ALWAYS maps ConcreteService1 to IService and ConcretePageService1 to IPageService regardless of controller type

 public class Controller1 : Controller { public Controller1(IService service, IPageService pageService) { } } public class Controller2 : Controller { public Controller2(IService service, IPageService pageService) { } } public interface IService { } public class ConcreteService1:IService { } public class ConcreteService2:IService { } public interface IPageService { } public class ConcretePageService1:IPageService { } public class ConcretePageService2:IPageService { } 
+6
c # structuremap
source share
2 answers

If this is just a separate registration, you can use named instances to map a specific instance to each controller.

 For<IService>().Add<ConcreteService1>().Named("service1"); For<IService>().Add<ConcreteService2>().Named("service2"); For<IPageService>().Add<PageService1>().Named("pageService1"); For<IPageService>().Add<PageService2>().Named("pageService2"); For<Controller1>().Use<Controller1>() .Ctor<IService>().Is(c => c.GetNamedInstance<IService>("service1")) .Ctor<IPageService>().Is( c => c.GetNamedInstance<IPageService>("pageService1")); For<Controller2>().Use<Controller2>() .Ctor<IService>().Is( c => c.GetNamedInstance<IService>("service2")) .Ctor<IPageService>().Is( c => c.GetNamedInstance<IPageService>("pageService2")); 

If this is a pattern that repeats in the application, you should use the type matching convention to avoid all this duplication.

Adding types named by type name is possible using the built-in convention.

 Scan(x => { x.AssembliesFromApplicationBaseDirectory(); x.AddAllTypesOf<IService>().NameBy(type => type.Name); x.AddAllTypesOf<IPageService>().NameBy(type => type.Name); x.WithDefaultConventions(); }); 
+12
source share

Take a look at the ConstructedBy () syntax for StructureMap.

On this page, but I'm not sure if these are the latest docs for SM:

http://structuremap.net/structuremap/InstanceExpression.htm#section18

Maybe I'm wrong about ConsructedBy - the docs are not very good. Look at the following question on a similar question:

Conditional use of StructureMap

0
source share

All Articles