基于Route在Controller中注入不同的实现

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

这是为了避免让我的控制器上的每个动作都读取“ language”参数并将其传递给我们。

从更高层次上讲,我想拥有这样的东西:

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。

iCMS 回答:基于Route在Controller中注入不同的实现

您可以在IServiceCollection(或ServiceRegistry,也实现IServiceCollection)上使用AddScoped重载,以向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),并且没有其他更改。

本文链接:https://www.f2er.com/1886301.html

大家都在问