Home > Software engineering >  Using Custom HeaderValue From Request to inject and register Services
Using Custom HeaderValue From Request to inject and register Services

Time:10-13

I would like to register a transient service that will be injected and used to instantiate controllers and other services.

The transient service's connection string depends up on different values coming from the request header. For example, the custom header will have two value UserId and UserName. Based on these values, I want to appropriately configure the service and register it.

My question is how can I pass the request header values to the class constructor ?

public class ServiceA: IServiceA
{
    public ServiceA(string userId, string userName)
    {
      // instantiate the service based on userId and userName
    }
}

I know I can create a middleware or filter but that is not where I need these values. I also dont want to pass these values as function argument so that i dont clutter the code base with usernames and userIds.

I saw IHttpContextAccessor can be used but MSFT cautions about performance issues when using this class.

What is the best approach to access request headers anywhere in the application other than the controllers ?

CodePudding user response:

You can safely create a scoped RequestMetadataService and in combination with ControllerExtensions class use IHttpContextAccessor

public static class ControllerExtensions
{
    public static string GetMyHeader(this HttpContext httpContext)
    {
        const string MyHeaderKey = "Key";
        if(! httpContext.Request.Headers.TryGetValue(MyHeaderKey, out var myValue))
            return null;

        return myValue;
    }
}

public class RequestMetadataService : IRequestMetadataService
{
    public HttpContext HttpContext { get; set; }
    public string MyValue 
    { 
        get => HttpContext?.GetMyHeader();
    }

    public RequestMetadataService(
        IHttpContextAccessor httpContextAccessor
    )
    {
        HttpContext = httpContextAccessor?.HttpContext;
    }
}

public class ServiceA: IServiceA
{
    public ServiceA(string userId, string userName)
    {
      var myValue = RequestMetadataService.MyValue;
    }
}

while using in Startup

services.AddHttpContextAccessor();
  • Related