2016-07-25 62 views
1

asp.net core docs中所述,您可以为请求本地化配置自定义提供程序。正如文档中所述:如何在ASP.NET Core的自定义本地化提供程序中注入DbContext?

假设您想让您的客户在数据库中存储他们的语言和文化。您可以编写一个提供程序来为用户查找这些值。

对于下面的代码片段在文档和GitHub的样品Localization.StarterWeb还提供:

services.Configure<RequestLocalizationOptions>(options => { 
var supportedCultures = new[] 
{ 
    new CultureInfo("en-US"), 
    new CultureInfo("fr") 
}; 

options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US"); 
options.SupportedCultures = supportedCultures; 
options.SupportedUICultures = supportedCultures; 

options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context => 
{ 
    // My custom request culture logic 
    // DbContext needed here <-- 
    return new ProviderCultureResult("en"); 
}));}); 

任何人能解释我如何注入一个DbContext从数据库加载用户特定的语言以上功能?

回答

3

那么,你不能通过构造函数注入它,因为你需要在ConfigureServices方法中实例化它,并且此时容器不可用。

相反,您可以通过HttpContext解决。

public class CustomRequestCultureProvider : RequestCultureProvider 
{ 
    // Note we don't inject any dependencies into it, so we can safely 
    // instantiate in ConfigureServices method 
    public CustomRequestCultureProvider() { } 

    public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext) 
    { 
     var dbContext = httpContext.RequestServices 
      .GetService<AppDbContext>(); 
    } 
} 

要知道,虽然这可能不是最优的,因为你必须在每次请求的数据库调用,所以也许这是值得摘要进一步和究竟你想使用的缓存策略取决于用DbContext做。

通常应避免在培养供应商的数据库调用,过滤器等性能方面的原因

更新:

还有就是GetService<T>一个通用版本,但需要通过using Microsoft.Extensions.DependencyInjection;导入命名空间。

+0

非常感谢您的回答!您提供的代码示例有两个小错误:构造函数前面的'class'关键字和'GetService'方法不是通用的,因此您必须调用'GetService(typeof(AppDbContext));' – MDummy

+0

用两个修复以及如何使用'GetService ' – Tseng

+0

感谢您澄清'GetService ' – MDummy

相关问题