gpt4 book ai didi

localization - 如何在 ASP.NET Core 的自定义本地化提供程序中注入(inject) DbContext?

转载 作者:行者123 更新时间:2023-12-04 04:02:38 25 4
gpt4 key购买 nike

asp.net core docs 中所述您可以为请求本地化配置自定义提供程序。如文档中所述:

Suppose you want to let your customers store their language and culture in your databases. You could write a provider to look up these values for the user.



为此,文档和 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");
}));});

谁能解释我如何注入(inject) DbContext在上述函数中从数据库加载用户特定语言?

最佳答案

好吧,你不能通过构造函数注入(inject)它,因为你需要在 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; 导入命名空间.

关于localization - 如何在 ASP.NET Core 的自定义本地化提供程序中注入(inject) DbContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38573236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com