简体   繁体   中英

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. I have defined my custom token Event handler class and have bound it to ASP.NET Core mechanism as below:

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

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. if I try to pass in IUserManager in TokenAuthenticationEvents an exception is raised that ASP.NET Core could not resolve IUserManager . So my question is

How do I tell ASP.NET Core DI to get the IUserManager resolved from Simple Injector? .

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. 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. 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. Those features are automatically enabled when you call .AddAspNetCore() . So you can reduce your configuration to the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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