如何使用 WebApplicationFactory 覆盖 Autofac 容器中的服务

2024-03-30

我正在使用 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());
}

你们中有人知道我该怎么做吗?

Thanks.


我有同样的问题,但我发现article https://andrewlock.net/converting-integration-tests-to-net-core-3/.

TL;DR

你必须继承自WebApplicationFactory<T>并覆盖CreateHost method.

所以对我来说它看起来像

public class MyWebApplicationFactory: WebApplicationFactory<Program>
{
    protected override IHost CreateHost(IHostBuilder builder)
    {
        builder.ConfigureContainer<ContainerBuilder>(ConfiguresContainer);
        return base.CreateHost(builder);
    }

    private void ConfiguresContainer(ContainerBuilder builder)
    {
        //add something extra to your container here
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 WebApplicationFactory 覆盖 Autofac 容器中的服务 的相关文章

随机推荐