Reputation: 2427
I have this class which gets Authorization Header value from Header and store it into variable like this:
public class AuthenticationHeader
{
private static IHttpContextAccessor _httpContextAccessor;
public AuthenticationHeader(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public string AuthHeader => _httpContextAccessor.HttpContext?.Request.Headers["Authorization"]
}
And I have registered this class for DI like this in my Startup.cs
services.AddScoped<AuthenticationHeader>();
And then this class is used in my NetworkClient using Constructor Injection.
public ClubMatasClient(HttpClient client, ILogger<ClubMatasClient> logger, AuthenticationHeader authHeader)
{
_client = client;
client.BaseAddress = new Uri("url");
client.DefaultRequestHeaders.Add("Accept", "application/json");
_logger = logger;
AuthToken = authHeader.AuthHeader;
}
I have read life cycle of Scoped
and Transient
in here docs and I am confused which one should I use. I don't want to mix my Authentication Headers that are coming in my Request headers.
Upvotes: 0
Views: 205
Reputation: 5530
Scoped is per http request, Transient is per type.
Since you Authorization Header is per request you can register AuthenticationHeader
class as Scoped that means all types created to serve your request will get the same instance.
But you can also register it as Transient, then all types created to serve you request will get new instance of AuthenticationHeader
that internally use IHttpContextAccessor that will give you the same HttpContext for your http request.
So you can use both, the only consideration is memory consumption. Scoped will use less memory.
Edit:
Actually you can also use Singleton because IHttpContextAccessor
registered as Singleton and internally it uses AsyncLocal to store current context. But I wouldn't recommend it because in future AuthenticationHeader
can be extended with some additional logic that will break the behavior.
Upvotes: 2