Home > Enterprise >  How to manually create controller as a service?
How to manually create controller as a service?

Time:01-18

I would like to create controllers as services, and additionally create them manually.

In order to do so, I added some code in "Startup" class, my "ConfigureServices" method starts with:

public void ConfigureServices(IServiceCollection services)
{
  services.AddSignalR();
  services.AddControllers()
    .AddControllersAsServices()
    .AddNewtonsoftJson();
  ...

AddControllersAsServices supposedly switches to controllers as services with transient lifetime. Knowing this I added:

...
services.AddTransient<MyController>(sp =>
{
  return new MyController(
    sp.GetService<ILogger>(),
    sp.GetService<Microsoft.AspNetCore.Authorization.IAuthorizationService>(),
    ...
});

but when I try to run it I get error on IHostBuilder Build method call (in "Program.cs"):

'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MyController Lifetime: Transient ImplementationType: MyController': A suitable constructor for type 'MyController' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.)'

"AddTransient" call is executed, but the body of it -- no, and judging by the error message it looks like the system relied on classic DI instead of the entry provided directly by me.

So how to force the usage of the entry I defined?

CodePudding user response:

Ok, finally I found it: https://github.com/dotnet/aspnetcore/issues/27959 Just before calling Build on "IHostBuilder" one has to call:

 .UseDefaultServiceProvider((context, options) =>
    {
        options.ValidateOnBuild = false;
    })
  •  Tags:  
  • Related