简体   繁体   English

使用AutoFac解析通用集合

[英]Resolving Generic Collections using AutoFac

I couldn't find a question talking about resolving a collection to base classes. 我找不到一个关于将集合解析为基类的问题。 I have the following pseudo test class which uses AutoFac to resolve handlers: 我有以下伪测试类,它使用AutoFac来解析处理程序:

namespace Test {

    interface IEventEmitter {}

    interface IEventHandler {}

    interface IEventHandler<in T> : IEventHandler where T: IEventEmitter {}

    interface ISomeClass : IEventEmitter {}

    class SomeClass : ISomeClass
    {
        // 2 handlers should be resolved here, not one!
        public SomeClass(IEnumerable<IEventHandler> handlers) {}
    }

    class GenericEventHandler : IEventHandler {}

    class DedicatedEventHandler : IEventHandler<ISomeClass> {}

    [TestClass]
    class TestClass
    {
        [TestMethod]
        private void TestHandlers()
        {
            var builder = new ContainerBuilder();

            // registered in order to resolve handlers
            builder.RegisterType<SomeClass>().As<ISomeClass>();

            builder.RegisterType<GenericEventHandler>().As<IEventHandler>();

            builder.RegisterType<DedicatedEventHandler>().As<IEventHandler<ISomeClass>>();

            var container = builder.Build();

            using (var scope = container.BeginLifetimeScope())
            {
                var instanceWithHandlers = scope.Resolve<ISomeClass>();
            }
        }
    }
}

Notice that I am registering a dedicated handler to ISomeClass interface, as well as a generic one for any type of event emitter. 请注意,我正在为ISomeClass接口注册一个专用处理程序,以及为任何类型的事件发射器注册一个通用处理程序。 My expectation is that SomeClass constructor will be injected with 2 handlers- the generic and the dedicated one. 我的期望是SomeClass构造函数将注入2个处理程序 - 通用和专用处理程序。

Unfortunately, that's not the case. 不幸的是,事实并非如此。 What am I doing wrong here? 我在这做错了什么?

Thanks. 谢谢。

When you register an interface with As Autofac does not automatically registers its base interfaces. 使用As Autofac注册接口时,不会自动注册其基本接口。

So you need to manually tell to Autofac that your DedicatedEventHandler is also an IEventHandler with: 所以你需要手动告诉Autofac你的DedicatedEventHandler也是一个IEventHandler

builder.RegisterType<DedicatedEventHandler>()
       .As<IEventHandler<ISomeClass>>()
       .As<IEventHandler>();

If you want to register a type with all its interfaces you can use the AsImplementedInterfaces method. 如果要注册具有其所有接口的类型,可以使用AsImplementedInterfaces方法。

So the equivalent of the above registration is the following: 所以相应的上述注册如下:

builder.RegisterType<DedicatedEventHandler>()
       .AsImplementedInterfaces();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM