我正在使用WebApplicationFactory编写一些集成测试。我使用Autofac作为我的依赖解析器。在我的测试中,我尝试覆盖其中一个注册以便可以模拟其中一个依赖项。使用aspnetcore默认的ConfigureServices方法很简单:
public static RestClient GetClient(Func<IDependency> dependencyFactory)
{
var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
{
builder.ConfigureServices(s =>
{
s.AddTransient<Func<IDependency>>(s=>dependencyFactory);
});
});
return GetRestClient(application.CreateClient());
}
但是,我想做的是使用Autofac ContainerBuilder 来完成同样的事情。代码可能类似于:
public static RestClient GetClient(Func<IDependency> dependencyFactory)
{
var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
{
builder.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
containerBuilder.Register<IDependency>(c=>dependencyFactory()).InstancePerDependency();
});
});
return GetRestClient(application.CreateClient());
}
你们中有人知道我该如何做到这一点吗?
谢谢。
UseServiceProviderFactory(new AutofacServiceProviderFactory())
后才会调用ConfigureContainer
方法。 - Travis Illig