본문 바로가기
Programming/.NET

[.NET Core] Custom Middleware의 Scoped lifetime 서비스 주입

by 째스터 2023. 1. 3.
728x90

Custom Middleware에서 Scoped lifetime의 서비스를 주입받는 경우에는
Constructor가 아니라 InvokeAsync 메서드에서 주입받아야 한다.

public class MyCustomMiddleware
{
    private readonly RequestDelegate _next;

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

    // IMessageWriter is injected into InvokeAsync
    public async Task InvokeAsync(HttpContext httpContext, IMessageWriter svc)
    {
        svc.Write(DateTime.Now.Ticks.ToString());
        await _next(httpContext);
    }
}

constructor에 파라미터를 추가했을 때 에러가 발생해서 찾아보는데 아래 문장 때문에 조금 헷갈렸다.

Additional parameters for the constructor and Invoke/InvokeAsync are populated by dependency injection (DI).

조금만 더 읽어볼걸...
돌고 돌아서 결국 MS documentation으로 돌아와서 알게 되었다.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-7.0#per-request-middleware-dependencies 

 

Write custom ASP.NET Core middleware

Learn how to write custom ASP.NET Core middleware.

learn.microsoft.com

 

728x90

댓글