參考 ABP設計UI菜單欄的源碼分析,抽出了ABP這塊自定義擴展的實現。在ABP的源碼裡面有很多地方都用到了這種設計方式,實現了用戶自定義擴展。 新建一個空的asp.net core項目,新建一個類,源碼: StartUp類源碼: 擴展點:在 中提供用戶自定義擴展點,完美的是下瞭解耦。 參考: "B ...
參考 ABP設計UI菜單欄的源碼分析,抽出了ABP這塊自定義擴展的實現。在ABP的源碼裡面有很多地方都用到了這種設計方式,實現了用戶自定義擴展。
新建一個空的asp.net core項目,新建一個類,源碼:
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DesignPatternSample.Infrastructure
{
public class LanguageInfo
{
public string CultureName { get; set; }
public string DisplayName { get; set; }
public LanguageInfo(string cultureName, string displayName)
{
CultureName = cultureName;
DisplayName = displayName;
}
}
public class AbpSampleOptions
{
public List<LanguageInfo> Languages { get; }
public AbpSampleOptions()
{
Languages = new List<LanguageInfo>();
}
}
public interface ILanguageProvider
{
Task<IReadOnlyList<LanguageInfo>> GetLanguagesAsync();
}
public class DefaultLanguageProvider : ILanguageProvider
{
protected AbpSampleOptions Options { get; }
public DefaultLanguageProvider(IOptions<AbpSampleOptions> options)
{
Options = options.Value;
}
public Task<IReadOnlyList<LanguageInfo>> GetLanguagesAsync()
{
return Task.FromResult((IReadOnlyList<LanguageInfo>)Options.Languages);
}
}
}
StartUp類源碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DesignPatternSample.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace DesignPatternSample
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
// 依賴註入
services.AddTransient<ILanguageProvider, DefaultLanguageProvider>();
// 配置多語言
services.Configure<AbpSampleOptions>(options =>
{
options.Languages.Add(new LanguageInfo( "cs", "Čeština"));
options.Languages.Add(new LanguageInfo("en", "English"));
options.Languages.Add(new LanguageInfo("pt-BR", "Português"));
options.Languages.Add(new LanguageInfo("tr", "Türkçe"));
options.Languages.Add(new LanguageInfo("zh-Hans", "簡體中文"));
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILanguageProvider provider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
// 測試
endpoints.MapGet("/Abp/Test", async context =>
{
var result = provider.GetLanguagesAsync();
var output = string.Join(",", result.Result.Select(s => s.CultureName).ToArray());
await context.Response.WriteAsync(output);
});
});
}
}
}
擴展點:在ConfigureService
中提供用戶自定義擴展點,完美的是下瞭解耦。
參考: