Reputation: 14098
In the past, I've worked on complex projects with lots of Autofac components. To check that everything could be resolved, we'd write a unit test that tries to resolve all necessary (top-level) components.
But now I'm trying to do this for the first time in an ASP.NET MVC project.
I've 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 leads to 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
Anyone have an idea how I can elegantly solve this? Should I fake a HttpRequest? How and where do I do that? Or are there other options?
Upvotes: 3
Views: 1432
Reputation: 23909
There are docs here on how to test per request dependencies.
Based on the comment thread in the question, it sounds like you switched your per request dependencies to per lifetime scope (which is how ASP.NET Core handles things now anyway).
For future readers of the question, there are actually a few options, so check out the docs for more.
Upvotes: 2