无法解析 Autofac 中的注册类型

Can't resolve a registered type in Autofac

我正在尝试为使用 Autofac 实现依赖注入的项目 (XUnit) 编写集成测试。具体来说,我正在尝试测试我的服务层。

这就是为什么我实现了一个“内核”class,它注册了所有组件并具有 returns 组件在参数中请求的方法。

public class TestKernel
    {
        private readonly IContainer container;

        public TestKernel()
        {
            var builder = new ContainerBuilder();
            builder.RegisterModule(new ApplicationServicesContainer());
            builder.RegisterModule(new SsspDomainContainer());
            container = builder.Build();
        }

        public T Get<T>() where T : class
        {
            return container.Resolve<T>();
        }
    }

注册服务的模块:

 public class ApplicationServicesContainer : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<XService>().As<IXService>();
                                .
                                .
                                .
        }
    }

然后在测试中我使用以下方法获取服务:

public class XServiceTest : TestKernel
    {
        private readonly XService _service;

        public XServiceTest()
        {
            _service = Get<XService>();
        }

在执行测试时出现以下错误:

Autofac.Core.Registration.ComponentNotRegisteredException : The requested service 'Project.ApplicationServices.Services.XService' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

非常感谢任何帮助

那是因为你请求的是XService,但是你把XService注册成了IXService接口。

你得改成

    public class XServiceTest : TestKernel
    {
        private readonly IXService _service;

        public XServiceTest()
        {
            _service = Get<IXService>();
        }
    }

将具体的class注册到容器中是完全有效的。例如,您可以这样做:

    builder.RegisterType<XService>().As<XService>();

那样的话,您就可以从容器中请求 XService 并且它会按规定工作。这通常不是您想做的,但在某些情况下可能是有益的。