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?
}
Dependency injection (DI) is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method.
ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.
To answer your question, there is no way. by definition, private constructors are inaccessible by other classes.
Frameworks that apply the Constrained Construction anti-pattern can make using Constructor Injection difficult. The main disadvantage to Constructor Injection is that if the class you're building is called by your current application framework, you might need to customize that framework to support it.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With