How to map same interface to different ConcreteClasses with StructureMap?

后端 未结 2 1979
攒了一身酷
攒了一身酷 2020-12-18 04:09

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

And when Controller2 is created,

2条回答
  •  被撕碎了的回忆
    2020-12-18 04:57

    If it's just an isolated registration you can use named instances to map a specific instance to each controller.

    For().Add().Named("service1");
    For().Add().Named("service2");            
    For().Add().Named("pageService1");
    For().Add().Named("pageService2");            
    For().Use()
      .Ctor().Is(c => c.GetNamedInstance("service1"))
      .Ctor().Is(
        c => c.GetNamedInstance("pageService1"));
    For().Use()
      .Ctor().Is(
        c => c.GetNamedInstance("service2"))
      .Ctor().Is(
        c => c.GetNamedInstance("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().NameBy(type => type.Name);
        x.AddAllTypesOf().NameBy(type => type.Name);
        x.WithDefaultConventions();
      });
    

提交回复
热议问题