AddControllersAsServices() connects MVC controller activation to a third-party dependency injection container such as Lamar. Use it when controller dependencies are registered with Lamar rather than the built-in container. section 31.3
Chain it after AddControllers() inside UseLamar(). Lamar can then create API controllers and their dependency trees through its container, while framework services remain registered through the familiar service collection methods. section 31.3
Listing 31.16 Configuring Lamar as a third-party DI container
builder.Host.UseLamar(services => #1 { services.AddAuthorization(); #2 services.AddControllers() #2 .AddControllersAsServices(); #3 services.Scan(_ => { #4 _.AssemblyContainingType(typeof(Program)); #4 _.WithDefaultConventions(); #4 }); #4 } #1 Configures your services in UseLamar() instead of on builder.Services #2 You can (and should) add ASP.NET Core framework services to the ServiceRegistry, as usual. #3 Required so that Lamar is used to build your web API controllers #4 Lamar can automatically scan your assemblies for services to register.
A complete configuration shows AddAuthorization(), AddControllers().AddControllersAsServices(), and Lamar assembly scanning together. section 31.3
