假设我有以下(简化的)对象模型:
public abstract class Message { } public class SimpleMessage:Message { } public class ComplexMessage:Message { } public interface IMessageHandler{ void Handle(Message message); } public class NonGenericMessageHandler1: IMessageHandler{ void Handle(Message message){ Console.WriteLine("hi dad!") } } public class NonGenericMessageHandler2: IMessageHandler{ void Handle(Message message){ Console.WriteLine("hi mom!") } } public class GenericMessageHandler<T> :IMessageHandler where T: Message>{ void Handle(Message message){ //do something cool with the generic } } public class MessageHandlerFactory: IMessageHandlerFactory{ public MessageHandlerFactory(IEnumerable<IMessageHandler> handlers){ } public IMessageHandler Create(Message message){ //return the right handler } }
这就是问题所在。注入 MessageHandlerFactory的IEnumerable<IMessageHandler>
autofac 仅包含IMessageHandler
.
如果我想要通用版本,我必须手动声明各种封闭版本,如下:
public MessageHandlerFactory(IEnumerable<IMessageHandler> handlers, MessageHandler<SimpleMessage> handler1, MessageHandler<ComplexMessage> handler2){ }
这是我连接 Autofac 的方式:
builder.RegisterAssemblyTypes(typeof (IMessageHandlerFactory).Assembly) .AsImplementedInterfaces() .AsSelf() .SingleInstance(); builder.RegisterGeneric(typeof (MessageHandler<>)).AsSelf().SingleInstance();
如何让 Autofac 传入所有IMessageHandler
实现者的统一集合,包括任何通用变体?