Search code examples
c#asp.net-core-webapisimple-injectorasp-net-core-spa-services

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?.


Solution

  • 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>());