StructureMap Auto registration for generic types using Scan

杀马特。学长 韩版系。学妹 提交于 2019-11-26 16:31:44

问题


I've got an interface:

IRepository<T> where T : IEntity

while im knocking up my UI im using some fake repository implementations that just return any old data.

They look like this:

public class FakeClientRepository : IRepository<Client>

At the moment im doing this:

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

but loads of times for all my IEntities. Is it possible to use Scan to auto register all my fake repositories for its respective IRepository?

Edit: this is as far as I got, but i get errors saying the requested type isnt registered :(

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

Thanks

Andrew


回答1:


There is an easier way to do this. Please see this blog posting for details: 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<>));
        });
    }
}

Doing it this way avoids having to create your own ITypeScanner or conventions.




回答2:


Thanks Chris, thats exactly what I needed. For clarity, heres what I did from your link:

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);
        }
    }
} 



回答3:


Take a look at this discussion from the StructureMap users group: http://groups.google.com/group/structuremap-users/browse_thread/thread/649f5324c570347d



来源:https://stackoverflow.com/questions/516892/structuremap-auto-registration-for-generic-types-using-scan

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