我正在使用 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());
}
Run Code Online (Sandbox Code Playgroud)
但是,我想做的是使用 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());
}
Run Code Online (Sandbox Code Playgroud)
你们中有人知道我该怎么做吗?
谢谢。