C# 如何使StructureMap自动注册基本接口?
我们工作中的存储库通常都是积垢的,分为C# 如何使StructureMap自动注册基本接口?,c#,dependency-injection,inversion-of-control,structuremap,C#,Dependency Injection,Inversion Of Control,Structuremap,我们工作中的存储库通常都是积垢的,分为ICreatable、iretriable、iupdatatable、和IDeletable。检索行为在检索时使用对象的主键。通常,我们最终会得到另一个子接口,用于处理存储库CRUD行为之外的方法。看起来是这样的: public interface IUserRepository : ICreatable<User>, IRetrievable<User>, IUpdatable<User> { IEnumerab
ICreatable
、iretriable
、iupdatatable
、和IDeletable
。检索行为在检索时使用对象的主键。通常,我们最终会得到另一个子接口,用于处理存储库CRUD行为之外的方法。看起来是这样的:
public interface IUserRepository : ICreatable<User>, IRetrievable<User>, IUpdatable<User>
{
IEnumerable<User> GetUsersWithoutEmail ();
}
public class UserRepository : IUserRepository
{
// implement members...
}
当我要求使用IUserRepository
或IRetrievable
时,我希望注入UserRepository
,而无需手动配置这4个存储库中的每一个。如果我决定ICreatable
需要成为createableuserrepository
,我希望能够覆盖一个,但通常我只希望它尽可能地在树上运行
这可行吗?我想你最终需要某种疯狂的逻辑对象来帮助你在StructureMap的顶层处理这类事情——我不知道有什么功能可以提供这种条件处理 所以你会看到这样的情况:
public class NestedInheritanceConvention : IRegistrationConvention
{
public void Process (Type type, Registry registry)
{
if (type.IsInterface)
return;
if (type.IsAbstract)
return;
if (type.IsSubclassOf (typeof(Registry)))
return;
foreach (var iface in type.GetInterfaces ())
{
registry.For (iface).Use (type);
}
}
}
这将使您的StructureMap调用看起来像:
public StructureMapRegistry ()
{
Scan (x =>
{
x.Convention<NestedInheritanceConvention> ();
});
}
公共结构映射注册表()
{
扫描(x=>
{
x、 公约();
});
}
public StructureMapRegistry ()
{
Scan (x =>
{
x.Convention<NestedInheritanceConvention> ();
});
}