【问题标题】:How to have ASP.NET Core DI to get the dependency resolved by Simple Injector?如何让 ASP.NET Core DI 获得 Simple Injector 解决的依赖关系?
【发布时间】:2019-07-10 07:58:12
【问题描述】:

在一个 ASP.NET Core web api 项目中,我使用了 Simple Injector 和 JwtBearer 令牌。我已经定义了我的自定义令牌事件处理程序类并将其绑定到 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,
        };
    });
}

这是我的班级令牌事件:

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);
    }
}

我使用 Simple Injector 作为我的 DI 容器

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

IUserManager 及其所有依赖项都在 Simple Injector 中注册。如果我尝试在TokenAuthenticationEvents 中传递IUserManager,则会引发ASP.NET Core 无法解析IUserManager 的异常。所以我的问题是

我如何告诉 ASP.NET Core DI 从 Simple Injector 中解析 IUserManager?.

【问题讨论】:

    标签: c# asp.net-core-webapi simple-injector asp-net-core-spa-services


    【解决方案1】:

    就像 Simple Injector cross wires ASP.NET Core 组件一样,您可以反过来做同样的事情,尽管您必须手动执行此操作。例如:

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

    【讨论】:

    • 能否将 ASPNET Core 在其 DI 中找不到的 Objects 的调用自动定向到 Simple Injector。可能还有许多其他依赖项。这意味着要让 ASPNET Core 找到它们,我们必须为它们中的每一个添加该行。
    • 由于 .NET Core 的 DI 容器的限制,这不能自动完成。不过,这应该不是问题,因为您需要在 .NET Core 提供的组件中注入的 Simple Injector 控制的服务数量应该是最少的。如果您经常需要此功能,则说明您的设置有问题。
    【解决方案2】:

    这个答案并没有解决您最初的问题,但我确实注意到您将旧的 Simple Injector ASP.NET Core 配置模型与新配置模型混合在一起。您目前有以下代码:

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

    不过,对 EnableSimpleInjectorCrossWiring 和 UseSimpleInjectorAspNetRequestScoping 的调用是旧 API,将在未来的版本中删除。当您拨打.AddAspNetCore() 时,这些功能会自动启用。因此,您可以将配置减少到以下内容:

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

    【讨论】:

    • 仅供参考,我们是否需要在纯基于 WebAPI 的项目中使用 AddViewComponentActivation() 和 AddTagHelperActivation()?我相信这与典型的网络应用程序而不是网络 API 有关?
    • 你是对的。在 Web API 项目中,您不需要那些扩展方法。事实上,您可能不需要包含这些方法的 tge 集成包。该包还依赖于许多您不需要的 ASP.NET 包。这些包被设置为付费播放联合模型 abd,这就是为什么有单独的方法。
    猜你喜欢
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多