3

我有一个 ASP.NET Core 应用程序,我想根据所选的 Route 使用不同的策略。例如,如果有人导航到 /fr/Index 我想将法语翻译实现注入我的控制器。同样,当有人导航到 /de/Index 时,我希望注入德语翻译。

这是为了避免让我的控制器上的每一个操作都读取“语言”参数并将其传递。

从更高的层次来看,我想要这样的东西:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Stuff here
    app.MapWhen(
        context => context.Request.Query["language"] == "fr", 
        builder =>
        {
            builder.Register<ILanguage>(FrenchLanguageImplementation);
        });

    app.MapWhen(
        context => context.Request.Query["language"] == "de",
        builder =>
        {
            builder.Register<ILanguage>(GermanLanguageImplementation);
        });
}

不幸的是,看起来我没有在该级别获得 IoC 容器解析上下文。

PS:我使用 Lamar 作为 IoC。

4

1 回答 1

2

您可以使用AddScoped重载 on IServiceCollection(或ServiceRegistry,它也实现IServiceCollection)向 DI 容器提供基于工厂的服务注册。这是 的示例实现ConfigureContainer,内联解释性注释:

public void ConfigureContainer(ServiceRegistry services)
{
    // ...

    // Register IHttpContextAccessor for use in the factory implementation below.
    services.AddHttpContextAccessor();

    // Create a scoped registration for ILanguage.
    // The implementation returned from the factory is tied to the incoming request.
    services.AddScoped<ILanguage>(sp =>
    {
        // Grab the current HttpContext via IHttpContextAccessor.
        var httpContext = sp.GetRequiredService<IHttpContextAccessor>().HttpContext;
        string requestLanguage = httpContext.Request.Query["language"];

        // Determine which implementation to use for the current request.
        return requestLanguage switch
        {
            "fr" => FrenchLanguageImplementation,
            "de" => GermanLanguageImplementation,
            _ => DefaultLanguageImplementation
        };
    });
}

免责声明:在测试此答案中的信息之前,我从未使用过 Lamar,因此此特定于 Lamar 的设置取自文档和最佳猜测。如果没有 Lamar,示例代码中的第一行将public void ConfigureServices(IServiceCollection services)没有其他更改。

于 2020-07-23T10:17:48.197 回答