How to map same interface to different ConcreteClasses with StructureMap?

最后都变了- 提交于 2019-11-29 07:21:55

If it's just an isolated 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's repeated in the application you should use a convention to map the types in order to avoid all this duplication.

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

Scan(x =>
  {
    x.AssembliesFromApplicationBaseDirectory();
    x.AddAllTypesOf<IService>().NameBy(type => type.Name);
    x.AddAllTypesOf<IPageService>().NameBy(type => type.Name);
    x.WithDefaultConventions();
  });
Phil Sandler

Look into the ConstructedBy() syntax for StructureMap.

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

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

I might be wrong about ConsructedBy--the docs aren't very good. Look at the following for a similar question:

StructureMap Conditional use

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!