2010-11-22 68 views
1

鉴于具体的类,并具有名称的接口不匹配StructureMap配置具体类,其接口名称不匹配

Harvester_JohnDeere_Parsley : AbstractMachine, IParsleyHarvester 
Harvester_NewHolland_Sage : AbstractMachine, ISageHarvester 
Harvester_Kubota_Rosemary : AbstractMachine, IRosemaryHarvester 

在接口都有一个共同的父

IParsleyHarvester : ISpiceHarvester 
ISageHarvester : ISpiceHarvester 
IRosemaryHarvester : ISpiceHarvester 

如何StructureMap被配置以便我的实例...收割机可以注入到构造函数中,例如

public ParsleyField(IParsleyHarvester parsleyHarvester) 

而不必在注册表中单独配置每对;例如

For<ISageHarvester>().Use<Harvester_NewHolland_Sage>(); 

我试过扫描

Scan(x => 
{ 
    x.AssemblyContainingType<Harvester_Kubota_Rosemary>(); 
    x.AddAllTypesOf<ISpiceHarvester>(); 

但我...收割机接口不被映射。

谢谢!

编辑

这两个答案的工作。 @ jeroenh的优点是可以添加guard子句来排除类(无论出于何种原因)。下面是一个基于@ Mac对this question的回答的例子。

public class HarvesterConvention : StructureMap.Graph.IRegistrationConvention 
{ 
    public void Process(Type type, Registry registry) 
    { 
     // only interested in non abstract concrete types 
     if (type.IsAbstract || !type.IsClass) 
      return; 

     // Get interface 
     var interfaceType = type.GetInterface(
      "I" + type.Name.Split('_').Last() + "Harvester"); 

     if (interfaceType == null) 
      throw new ArgumentNullException(
       "type", 
       type.Name+" should implement "+interfaceType); 

     // register (can use AddType overload method to create named types 
     registry.AddType(interfaceType, type); 
    } 
} 

用法:

Scan(x => 
{ 
    x.AssemblyContainingType<Harvester_Kubota_Rosemary>(); 
    x.Convention<HarvesterConvention>(); 
    x.AddAllTypesOf<ISpiceHarvester>(); 

回答

1

StructureMap不知道你的约定。您需要通过添加自定义注册约定来告诉它。实现IRegistrationConvention接口,约定添加到组装扫描仪:

Scan(x => 
    { 
    x.Convention<MyConvention>(); 
    } 
1

我改编自@ Kirschstein的回答解决this question

Scan(x => 
{ 
    x.AssemblyContainingType<Harvester_Kubota_Rosemary>(); 
    x.AddAllTypesOf<ISpiceHarvester>() 
    .NameBy(type => "I" + type.Name.Split('_').Last() + "Harvester"); 

定义将具体类的名称转换为其接口名称以进行查找的方式。