在structure-map 3中为DecorateAllWith()方法定义filter

我使用以下语句来装饰我的所有ICommandHandlersDecorator1

 ObjectFactory.Configure(x => { x.For(typeof(ICommandHandler)).DecorateAllWith(typeof(Decorator1)); }); 

但是因为Decorator1实现了ICommandHandlers ,所以Decorator1类也会自行修饰。

所以,问题是当我注册所有ICommandHandler时, Decorator1无意中注册。 我怎样才能过滤DecorateWithAll()以装饰除Decorator1之外的所有ICommandHandler Decorator1

ObjectFactory已过时。

您可以将Decorator1<>排除在注册为vanilla 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<>)); }); 

UPDATE

对于多个模块,您可以使用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<>)); } } 

只有Composition Root需要知道所有Registry实现。

  var container = new Container(config => { config.AddRegistry(); }); 

您甚至可以选择在运行时查找所有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(); foreach (var registry in registries) { config.AddRegistry(registry); } });