liveBook · Manning

AddControllersAsServices()

As explained in ASP.NET Core in Action, 3e

AddControllersAsServices() is an ASP.NET Core MVC extension method that registers controller types as services in the dependency injection container.

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains its placement after AddControllers() and its controller-activation rationale, but defers the underlying activation implementation details.
Examples
Shows AddAuthorization(), AddControllers().AddControllersAsServices(), and Lamar assembly scanning inside UseLamar().
What you can do after
Configure Lamar to resolve ASP.NET Core MVC controller dependencies through its container.
How it connects
Connects controller activation with dependency injection, AddControllers(), Lamar, and IServiceCollection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.