2009-02-05 118 views
9

泛型类型StructureMap自动注册我有一个接口:使用扫描

IRepository<T> where T : IEntity 

,而即时通讯使用一些假信息库实现,刚刚返回任何旧的数据敲开了我的UI IM。

他们看起来像这样:

public class FakeClientRepository : IRepository<Client> 

目前IM这样做:

ForRequestedType<IRepository<Client>>() 
    .TheDefaultIsConcreteType<FakeRepositories.FakeClientRepository>(); 

我所有IEntities负荷次,但。是否有可能使用扫描自动注册所有我的假的存储库为其各自的IRepository?

编辑:这是据我得到的,但我得到的错误说法请求类型的心不是注册:(

Scan(x => 
{ 
    x.TheCallingAssembly(); 
    x.IncludeNamespaceContainingType<FakeRepositories.FakeClientRepository>(); 
    x.AddAllTypesOf(typeof(IRepository<>)); 
    x.WithDefaultConventions(); 
}); 

感谢

安德鲁

回答

13

有一个更简单的方法来做到这一点。请参阅本博客中的详细信息:Advanced StructureMap: connecting implementations to open generic types

public class HandlerRegistry : Registry 
{ 
    public HandlerRegistry() 
    { 
     Scan(cfg => 
     { 
      cfg.TheCallingAssembly(); 
      cfg.IncludeNamespaceContainingType<FakeRepositories.FakeClientRepository>(); 
      cfg.ConnectImplementationsToTypesClosing(typeof(IRepository<>)); 
     }); 
    } 
} 

这样做,这样避免了必须创建自己的ITypeScanner或约定。

6

谢谢Chris,这正是我所需要的。为了清楚起见,继承人我d编号从您的链接:

Scan(x => 
{ 
    x.TheCallingAssembly(); 
     x.IncludeNamespaceContainingType<FakeRepositories.FakeClientRepository>(); 
    x.With<FakeRepositoryScanner>(); 
}); 


private class FakeRepositoryScanner : ITypeScanner 
{ 
    public void Process(Type type, PluginGraph graph) 
    { 
     Type interfaceType = type.FindInterfaceThatCloses(typeof(IRepository<>)); 
     if (interfaceType != null) 
     { 
      graph.AddType(interfaceType, type); 
     } 
    } 
}