我使用以下语句用ICommandHandlers<>
装饰我的所有Decorator1<>
:
ObjectFactory.Configure(x =>
{
x.For(typeof(ICommandHandler<>)).DecorateAllWith(typeof(Decorator1<>));
});
但由于Decorator1<>
实现ICommandHandlers<>
,Decorator1<>
类也会自行修饰。
所以,当我注册所有Decorator1
时,问题是ICommandHandler<>
无意中注册了。
如何过滤DecorateWithAll()
来装饰除ICommandHandler<>
以外的所有Decorator1<>
?
答案 0 :(得分:1)
ObjectFactory
已过时。
您可以排除Decorator1<>
注册为香草ICommandHandler<>
,代码如下:
var container = new Container(config =>
{
config.Scan(scanner =>
{
scanner.AssemblyContainingType(typeof(ICommandHandler<>));
scanner.Exclude(t => t == typeof(Decorator1<>));
scanner.ConnectImplementationsToTypesClosing(typeof(ICommandHandler<>));
});
config.For(typeof(ICommandHandler<>)).DecorateAllWith(typeof(Decorator1<>));
});
<强>更新强>
对于多个模块,您可以使用The Registry DSL撰写应用程序的一部分
using StructureMap;
using StructureMap.Configuration.DSL;
public class CommandHandlerRegistry : Registry
{
public CommandHandlerRegistry()
{
Scan(scanner =>
{
scanner.AssemblyContainingType(typeof(ICommandHandler<>));
scanner.Exclude(t => t == typeof(Decorator1<>));
scanner.ConnectImplementationsToTypesClosing(typeof(ICommandHandler<>));
});
For(typeof(ICommandHandler<>)).DecorateAllWith(typeof(Decorator1<>));
}
}
只有组合根需要了解所有Registry
实现。
var container = new Container(config =>
{
config.AddRegistry<CommandHandlerRegistry>();
});
您甚至可以选择在运行时查找所有Registry
实例(您仍需要确保加载所有必需的程序集)
var container = new Container(config =>
{
var registries = (
from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.DefinedTypes
where typeof(Registry).IsAssignableFrom(type)
where !type.IsAbstract
where !type.Namespace.StartsWith("StructureMap")
select Activator.CreateInstance(type))
.Cast<Registry>();
foreach (var registry in registries)
{
config.AddRegistry(registry);
}
});