I want to verify dependencies are properly configured for all Controllers in an ASP.NET 6 Web App.
Assuming I have invoked .AddControllersAsServices()
,
I can call app.Services.GetRequiredService<HomeController>()
from Main
and it succeeds.
public class Program
{
public static WebApplication BuildApp(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews()
.AddControllersAsServices();
var app = builder.Build();
return app;
}
public static void Main(string[] args)
{
WebApplication app = BuildApp(args);
app.Services.GetRequiredService<HomeController>(); // This succeeds!
// <snip>
app.Run();
}
}
But it fails when called from a unit test.
[Fact]
public void Test1()
{
var app = Program.BuildApp(Array.Empty<string>());
app.Services.GetRequiredService<HomeController>(); // This fails!
}
System.InvalidOperationException: 'No service for type 'TryControllersAsServices.Controllers.HomeController' has been registered.'
What is the difference between calling from Main versus a unit test?