【问题标题】:How to write a unit test (or regression test) for InstancePerRequest services in Autofac如何在 Autofac 中为 InstancePerRequest 服务编写单元测试(或回归测试)
【发布时间】:2017-04-27 19:07:21
【问题描述】:

过去,我曾参与过包含大量 Autofac 组件的复杂项目。为了检查是否可以解决所有问题,我们将编写一个单元测试来尝试解决所有必要的(顶级)组件。

但现在我第一次尝试在 ASP.NET MVC 项目中执行此操作。

我已经像这样注册了我的 ApiController:

builder.RegisterType<MyController>().InstancePerRequest();

我想像这样测试:

var containerBuilder = new ContainerBuilder();
foreach (var module in ModuleRepository.GetModulesForWebsite())
{
    containerBuilder.RegisterModule(module);
}

var container = containerBuilder.Build();

foreach (var componentRegistryRegistration in container.ComponentRegistry.Registrations)
{
    foreach (var service in componentRegistryRegistration.Services.OfType<TypedService>())
    {
        if (service.ServiceType.IsAssignableTo<ApiController>())
        {
            var implementation = container.Resolve(service.ServiceType);
            implementation.Should().NotBeNull();
        }
    }
}

但是,这会导致这个异常:

Autofac.Core.DependencyResolutionException: Unable to resolve 
the type 'Website.APIControllers.Clean.IngredientsController' 
because the lifetime scope it belongs in can't be located. The 
following services are exposed by this registration:
- MyProject.MyController

有人知道我该如何优雅地解决这个问题吗?我应该伪造一个 HttpRequest 吗?我如何以及在哪里这样做?还是有其他选择?

【问题讨论】:

标签: c# unit-testing dependency-injection autofac


【解决方案1】:

There are docs here on how to test per request dependencies.

根据问题中的评论线程,听起来您将每个请求依赖项切换到每个生命周期范围(无论如何,这就是 ASP.NET Core 现在处理事情的方式)。

对于问题的未来读者,实际上有几个选项,因此请查看文档了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 2016-09-28
    相关资源
    最近更新 更多