How to override a service in Autofac container using WebApplicationFactory

Viewed 74

I'm writing some integration testing using WebApplicationFactory. I use Autofac as my dependency resolver. In my test, I'm trying to override one of the registration so I can mock one of the dependency. It's pretty simple using the aspnetcore default ConfigureServices method :

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());
}

But, what I'm trying to do is to do the same thing using the Autofac ContainerBuilder. Something that would look like :

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());
}

Any of you know how I can do this ?

Thanks.

0 Answers
Related