How to write a unit test (or regression test) for InstancePerRequest services in Autofac

In the past I have worked on complex projects with a lot of Autofac components. To check that everything can be resolved, we will write a unit test that tries to resolve all the necessary (upstream) components.

But now I am trying to do this for the first time in an ASP.NET MVC project.

I registered my ApiControllers like this:

builder.RegisterType<MyController>().InstancePerRequest();

      

And I thought to test like this:

var containerBuilder = new ContainerBuilder();
foreach (var module in ModuleRepository.GetModulesForWebsite())
{
    containerBuilder.RegisterModule(module);
}

var container = containerBuilder.Build();

foreach (var componentRegistryRegistration in container.ComponentRegistry.Registrations)
{
    foreach (var service in componentRegistryRegistration.Services.OfType<TypedService>())
    {
        if (service.ServiceType.IsAssignableTo<ApiController>())
        {
            var implementation = container.Resolve(service.ServiceType);
            implementation.Should().NotBeNull();
        }
    }
}

      

However, this results in this exception:

Autofac.Core.DependencyResolutionException: Unable to resolve 
the type 'Website.APIControllers.Clean.IngredientsController' 
because the lifetime scope it belongs in can't be located. The 
following services are exposed by this registration:
- MyProject.MyController

      

Does anyone have an idea how I can gracefully solve this? Should I spoof the HttpRequest? How and where do I do it? Or are there other options?

+3


source to share


1 answer


There are docs here on how to test the dependencies of each request.

Based on the thread of comments in this question, it sounds like you've switched dependencies on every request for the entire life area (since ASP.NET Core handles everything anyway anyway).



There are several options for future readers of the question, so check out the docs for more.

+2


source







All Articles