IGeekFan.Localization.FreeSql
基于数据库的本地化,支持多语言应用。
功能概览
| 功能 | 说明 |
|---|---|
| 多语言支持 | 基于数据库的本地化 |
| 动态管理 | 翻译内容后台可编辑 |
安装
dotnet add package IGeekFan.Localization.FreeSql
dotnet add package FreeSql.Provider.Sqlite
数据模型
| 表 | 说明 |
|---|---|
LocalCulture | 语言定义(en-US、zh-CN 等) |
LocalResource | 翻译资源(Key-Value) |
快速开始
场景:多语言博客
1. 配置 FreeSql
public static IServiceCollection AddFreeSql(this IServiceCollection services, IConfiguration c)
{
IFreeSql fsql = new FreeSqlBuilder()
.UseConnectionString(DataType.Sqlite, c["ConnectionStrings:DefaultConnection"])
.UseAutoSyncStructure(true)
.Build();
services.AddSingleton(fsql);
return services;
}
// Program.cs
builder.Services.AddFreeSql(builder.Configuration);
2. 替换本地化服务
builder.Services.AddSingleton<IStringLocalizerFactory, FreeSqlStringLocalizerFactory>();
builder.Services.TryAddTransient(typeof(IStringLocalizer<>), typeof(StringLocalizer<>));
3. 配置语言
var supportedCultures = new List<CultureInfo>
{
new("en-US"),
new("zh-CN"),
new("ja-JP")
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("zh-CN"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
4. 种子数据
fsql.CodeFirst.Entity<LocalCulture>(e =>
{
e.HasData(new List<LocalCulture>
{
new("en-US", "English"),
new("zh-CN", "中文")
{
Resources = new List<LocalResource>
{
new("Hello", "你好"),
new("Welcome", "欢迎")
}
}
});
});
5. 使用
[ApiController]
[Route("api/[controller]")]
public class HomeController : ControllerBase
{
private readonly IStringLocalizer<HomeController> _localizer;
public HomeController(IStringLocalizer<HomeController> localizer) => _localizer = localizer;
[HttpGet]
public string Get()
{
return _localizer["Hello"]; // 根据当前语言返回 "Hello" 或 "你好"
}
}
数据库配置
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=app.db"
}
}