结构图IRegistration注册非默认命名约定? [英] StructureMap IRegistrationConvention to register non default naming convention?
问题描述
我目前有一堆存储库,例如
IMyRepository
IAnotherRepository
它们都继承自IRepository(如果这有帮助)
如何获得结构图使用IRegistryConvention扫描器注册我的具体类型
SqlMyRepository
SqlAnotherRepository
我读过这篇文章没有给我什么我需要。 AddAllTypesOf针对IRepositoryInterface注册了所有具体类型,但是我要求每个具体类型都使用等效命名注册到接口。
ie。
对于< IMyRepository>()。Use< SqlMyRepository>();
还需要为测试库创建一些命名实例。
对于< IMyRepository>()。使用< TestMyRepository>()。
这是我想出的,看起来像我需要的工作。
public class SqlRepositoryConvention:StructureMap.Graph.IRegistrationConvention
{
public void Process(Type type,注册表注册表)
{
//只关注具有匹配命名接口的非抽象具体类型,并以Sql开头
if(type.IsAbstract ||!type.IsClass || type.GetInterface(type.Name.Replace (Sql,I))== null)
return;
//获取接口和注册(可以使用AddType重载方法创建命名类型
类型interfaceType = type.GetInterface(type.Name.Replace(Sql,I)) ;
registry.AddType(interfaceType,type);
}
}
并实施如下
扫描(cfg =>
{
cfg.TheCallingAssembly );
cfg.Convention< SqlRepositoryConvention>();
});
I currently have a bunch of repositories like so
IMyRepository
IAnotherRepository
They all inherit from IRepository (if this helps)
How can I get structuremap to use an IRegistryConvention scanner to register my concrete types which are named
SqlMyRepository
SqlAnotherRepository
I had read that article but it didn't give me quite what I needed. The AddAllTypesOf registered all the concrete types against the IRepositoryInterface but instead I require that each concrete type is registered against the interface with equivilent naming. ie.
For<IMyRepository>().Use<SqlMyRepository>();
Also I need to create some named instances for test repositories.
For<IMyRepository>().Use<TestMyRepository>().Named("Test");
Here's what I came up with which appears to work as I need it.
public class SqlRepositoryConvention : StructureMap.Graph.IRegistrationConvention
{
public void Process(Type type, Registry registry)
{
// only interested in non abstract concrete types that have a matching named interface and start with Sql
if (type.IsAbstract || !type.IsClass || type.GetInterface(type.Name.Replace("Sql", "I")) == null)
return;
// Get interface and register (can use AddType overload method to create named types
Type interfaceType = type.GetInterface(type.Name.Replace("Sql","I"));
registry.AddType(interfaceType, type);
}
}
And implemented as follows
Scan(cfg =>
{
cfg.TheCallingAssembly();
cfg.Convention<SqlRepositoryConvention>();
});
这篇关于结构图IRegistration注册非默认命名约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!