2

In my Startup class I a have method for RegisterAssemblyTypes through autofac as the following:

public class Startup
{
    public void ConfigureContainer(ContainerBuilder builder)
    {
        builder.RegisterModule(new ApplicationModule());
    }
}

public class ApplicationModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder
            .RegisterAssemblyTypes(
                typeof(EventHandler).GetTypeInfo().Assembly)
                .AsClosedTypesOf(typeof(IIntegrationEventHandler<>));
    }
}

What is the suggested way of registering assemblies using Autofac (e.g., RegisterAssemblyTypes) when the Startup class is called from integration tests; e.g.,

public class IntegrationTestApplicationFactory : WebApplicationFactory<Startup>
{ }

I am using Autofac 4.9.4.

Question:

how do you register an assembly type in WebApplicationFactory<Startup> using Autofac?

Dr. Strangelove
  • 2,725
  • 3
  • 34
  • 61
  • 1
    You can have a look at this GitHub [thread](https://github.com/autofac/Autofac/issues/332), as well as at [this](https://kolevsays.wordpress.com/2013/06/06/testing-autofac-magic/) and [this](http://blog.simpletrees.com/2014/09/unit-testing-and-autofac.html) articles – Pavel Anikhouski Dec 17 '19 at 18:39
  • 1
    any concrete examples? – Dr. Strangelove Dec 17 '19 at 21:28
  • 1
    Isn't the point of WebApplicationFactory that it loads a 'fake' server, but with all the same container configuration? Can you describe what problem you are seeing when you run this code? – Alistair Evans Dec 19 '19 at 09:27
  • 1
    I am trying to register an assembly type via autofac from test project. I generally call `builder.RegisterModule(new ApplicationModule())` from a method named `ConfigureContainer(ContainerBuilder builder)` in `Startup`. My question is how I can call a similar methods for registering assemblies from `WebApplicationFactory`. – Dr. Strangelove Dec 19 '19 at 17:54

1 Answers1

3

Due to incomplete documentation and a very poor support from Autofac maintainers, we decided to revert Autofac usage throughout all the projects in our institute.

Now we use ASP.NET Core's built-in registration, which works as expected when called in either of the following methods:

public class IntegrationTestApplicationFactory : WebApplicationFactory<Startup>
{
    protected override IHost CreateHost(IHostBuilder builder)
    {
        // register services here,
        // or in the ConfigureWebHost method
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            services.AddTransient<YourServiceType>();
        }
    }
}
Dr. Strangelove
  • 2,725
  • 3
  • 34
  • 61