简体   繁体   English

如何让 ASP.NET Core DI 得到 Simple Injector 解析的依赖?

[英]How to have ASP.NET Core DI to get the dependency resolved by Simple Injector?

In an ASP.NET Core web api project I'm using Simple Injector and JwtBearer tokens.在 ASP.NET Core web api 项目中,我使用了 Simple Injector 和 JwtBearer 令牌。 I have defined my custom token Event handler class and have bound it to ASP.NET Core mechanism as below:我已经定义了我的自定义令牌事件处理程序类并将其绑定到 ASP.NET Core 机制,如下所示:

private void ConfigureSecurity(IServiceCollection services)
{
    var encodedKey = Encoding.UTF8.GetBytes(_config[Konstants.SecretKey]);
    var key = new SymmetricSecurityKey(encodedKey);

    services.AddTransient<TokenAuthenticationEvents>();
    var authentication = services.AddAuthentication(o =>
    {
        o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        o.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    });

    authentication.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
    {
        options.SaveToken = true;
        options.EventsType = typeof(TokenAuthenticationEvents);
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateAudience = true,
            ValidAudience = _config[Konstants.AudienceKey],
            ValidateIssuer = true,
            ValidIssuer = _config[Konstants.AuthorityKey],
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = key,
            RequireExpirationTime = true,
            ValidateLifetime = true,
        };
    });
}

Here is my class Token Events:这是我的类令牌事件:

public class TokenAuthenticationEvents : JwtBearerEvents
{
    private readonly ILogger _log;
    private readonly IUserManager _users;


    public TokenAuthenticationEvents(ILogger log)
    {
        _log = log ?? throw new ArgumentNullException(nameof(log));
        _users = null;
    }

    public override Task TokenValidated(TokenValidatedContext context)
    {
        //Some Custom Logic that requires IUserManager 

        return base.TokenValidated(context);
    }
}

I'm using Simple Injector as my DI container我使用 Simple Injector 作为我的 DI 容器

services.AddSimpleInjector(container, options =>
{
    options
        .AddAspNetCore()
        .AddControllerActivation()
        .AddViewComponentActivation()
        .AddPageModelActivation()
        .AddTagHelperActivation();
    });
    services.EnableSimpleInjectorCrossWiring(container);
    services.UseSimpleInjectorAspNetRequestScoping(container);

IUserManager along with all its dependencies is registered in Simple Injector. IUserManager及其所有依赖项都在 Simple Injector 中注册。 if I try to pass in IUserManager in TokenAuthenticationEvents an exception is raised that ASP.NET Core could not resolve IUserManager .如果我尝试在IUserManager中传入IUserManagerTokenAuthenticationEvents引发异常,即 ASP.NET Core 无法解析IUserManager So my question is所以我的问题是

How do I tell ASP.NET Core DI to get the IUserManager resolved from Simple Injector?如何告诉 ASP.NET Core DI 从 Simple Injector 解析IUserManager . .

Just as Simple Injector cross wires ASP.NET Core components, you can do the same the other way around, although you will have to do this manually.就像 Simple Injector交叉连接ASP.NET Core 组件一样,您可以反过来做同样的事情,尽管您必须手动执行此操作。 For instance:例如:

services.AddScoped<IUserManager>(c => container.GetInstance<IUserManager>());

This answer doesn't solve your initial problem, but I did notice you are mixing the old Simple Injector ASP.NET Core configuration model with the new.这个答案并没有解决您最初的问题,但我确实注意到您将旧的 Simple Injector ASP.NET Core 配置模型与新的混合使用。 You currently have the following code:您目前拥有以下代码:

    services.AddSimpleInjector(container, options =>
    {
        options
            .AddAspNetCore()
                .AddControllerActivation()
                .AddViewComponentActivation()
                .AddPageModelActivation()
                .AddTagHelperActivation();
        });

        services.EnableSimpleInjectorCrossWiring(container);
        services.UseSimpleInjectorAspNetRequestScoping(container);

The calls to EnableSimpleInjectorCrossWiring and UseSimpleInjectorAspNetRequestScoping , however, are the old API and will be removed in a future release.但是,对EnableSimpleInjectorCrossWiringUseSimpleInjectorAspNetRequestScoping的调用是旧 API,将在未来版本中删除。 Those features are automatically enabled when you call .AddAspNetCore() .当您调用.AddAspNetCore()时,这些功能会自动启用。 So you can reduce your configuration to the following:因此,您可以将配置减少到以下内容:

    services.AddSimpleInjector(container, options =>
    {
        options
            .AddAspNetCore()
                .AddControllerActivation()
                .AddViewComponentActivation()
                .AddPageModelActivation()
                .AddTagHelperActivation();
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM