【发布时间】: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 吗?我如何以及在哪里这样做?还是有其他选择?
【问题讨论】:
-
啊,是的,现在我有了:) 我选择了
InstancePerLifetimeScopeoption。随意添加此作为答案并获得甜蜜的声誉积分。
标签: c# unit-testing dependency-injection autofac