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?