11

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

For example:

  • Create Authorization Service
  • Inject the current HTTP header(X-Api-Key) in constructor
  • In the implementation check if I have access

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?
}
4

1 Answer 1

8

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;
   }
}
1
  • 2
    I like this - injecting a class - more than injecting a value unless the value is something unchanging like a connection string. With any given DI container it's usually easier to inject a class than to configure the container to retrieve a value at runtime. Aug 2, 2016 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.