Brad
Brad

Reputation: 10660

Inject services into method in ASP.NET Core 2.x

I'm looking for information on how to dynamically inject services into a class method using Dependency injection in ASP.Net Core.

For example, in ASP Middleware, you can inject any number of services into the the Invoke method, as opposed to the constructor. This documentation explains how you can inject scoped services into your Middeware's Invoke method:

public class CustomMiddleware
{
    private readonly RequestDelegate _next;

    public CustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    // IMyScopedService is injected into Invoke
    public async Task Invoke(HttpContext httpContext, IMyScopedService svc)
    {
        svc.MyProperty = 1000;
        await _next(httpContext);
    }
}

I would like to mimic the same behavior in my own code, but I cannot find any documentation explain how to achieve this. Currently I am creating a scope using IServiceProvider.CreateScope and passing the resulting IServiceProvider as a parameter to my function defined below:

public async Task DoWork(IServiceProvider services, CancellationToken cancellationToken)
        {
            var logger = services.GetRequiredService<ILogger<RoomController>>();
            logger.LogInformation("Starting Room Controller.");
            while (!cancellationToken.IsCancellationRequested)
            {

                logger.LogInformation("Room still running");
                Thread.Sleep(5000);
            }
        }

I would like my function to look more like this:

public async Task DoWork(CancellationToken cancellationToken, ILogger<RoomController> logger)
        {
            logger.LogInformation("Starting Room Controller.");
            while (!cancellationToken.IsCancellationRequested)
            {

                logger.LogInformation("Room still running");
                Thread.Sleep(5000);
            }
        }

Any ideas?

Upvotes: 0

Views: 2489

Answers (2)

Marlon
Marlon

Reputation: 2139

I was also curious so I went digging into github to see how it's done for middleware. Turns out it's largely a manual process:

https://github.com/aspnet/AspNetCore/blob/425c196cba530b161b120a57af8f1dd513b96f67/src/Http/Http.Abstractions/src/Extensions/UseMiddlewareExtensions.cs

(Not copying the code here as it's quite a lot)

They inspect the method signature and compile a factory delegate which retrieves the required services from the IServiceProvider which lives in the HttpContext.

Upvotes: 2

Belurd
Belurd

Reputation: 782

Hope Dependency injection in ASP.NET Core can help :

  • Registration of the dependency in a service container. ASP.NET Core provides a built-in service container, IServiceProvider. Services are registered in the app's Startup.ConfigureServices method.

You need to register in ConfigureService how you dependency injection should be resolved.

Upvotes: 0

Related Questions