Sta*_*tan 11 c# dependency-injection .net-core asp.net-core
我看到了很多关于如何在.NET Core中使用DI的代码示例,但是没有一个使用构造函数参数.
例如:
在这里,我不仅需要在我的DI上使用DI,IAuthorizationService还需要在构造函数中注入令牌.我知道如何在Ninject中完成它,但是没有.NET Core DI的经验.
以下是我的例子.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddEntityFrameworkSqlite();
services.AddDbContext<MainDbContext>();
services.AddScoped<IAuthorizationService, AuthorizationService>(); // Inject current HttpContext header value as a constructor?
}
Run Code Online (Sandbox Code Playgroud)
我通常通过一个服务来传递这些值,其中数据是在一个中间件中设置的.例如:
可以注入的访问者类:
public class ApiKeyAccessor
{
public string ApiKey { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
以及在请求开始时设置API密钥的中间件:
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..
}
}
Run Code Online (Sandbox Code Playgroud)
现在我们只需要添加ApiKeyAccessor带有作用域生命周期的DI容器并将其添加ApiKeyMiddleware到请求执行管道中,最好尽快.
正确配置后,我们可以ApiKeyAccessor在控制器或服务中注入实例:
public class AuthorizationService
{
private readonly string _apiKey;
public AuthorizationService(ApiKeyAccessor apiKeyAccessor)
{
_apiKey = apiKeyAccessor.ApiKey;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4722 次 |
| 最近记录: |