Stan
Stan

Reputation: 26511

Dependency injection with constructor parameter in .net core

I see a lot of code examples on how to use DI in .NET Core, however none of them use constructor parameters.

For example:

Here I need to not only use DI on my IAuthorizationService but also inject the token in the constructor. I know how to do it in Ninject, however have no experience in .NET Core DI.

Here is what I have as an example.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddEntityFrameworkSqlite();
    services.AddDbContext<MainDbContext>();
    services.AddScoped<IAuthorizationService, AuthorizationService>(); // Inject current HttpContext header value as a constructor?
}

Upvotes: 11

Views: 5842

Answers (1)

Henk Mollema
Henk Mollema

Reputation: 46631

I usually flow such values through a service where the data is set in a piece of middleware. For example:

An accessor class which can be injected:

public class ApiKeyAccessor
{
    public string ApiKey { get; set; }
}

And a middleware which sets the API key at the beginning of the request:

public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;

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

    public Task Invoke(HttpContext context, ApiKeyAccessor apiKeyAccessor)
    {
        StringValues key;
        if (context.Request.Headers.TryGetValue("X-Api-Key", out key))
        {
            apiKeyAccessor.ApiKey = key;
            return _next(context);
        }

        // todo: throw exception, etc..
    }
}

Now all we have to is add the ApiKeyAccessor to the DI container with a scoped lifetime and add the ApiKeyMiddleware to the request execution pipeline, preferably as soon as possible.

When configured correctly, we can inject the ApiKeyAccessor instance in controllers or services:

public class AuthorizationService
{
   private readonly string _apiKey;

   public AuthorizationService(ApiKeyAccessor apiKeyAccessor)
   {
      _apiKey = apiKeyAccessor.ApiKey;
   }
}

Upvotes: 8

Related Questions