插件如何读取指定配置结点
先看效果
appsettings.json
{
"Plugin1": {
"Test1": "11111111"
},
"Plugin2": {
"Test2": "22222222"
}
}
为每个节点创建Option
public class Service1Options
{
public string Test1 { get; set; }
}
public class Service2Options
{
public string Test2 { get; set; }
}
插件,每个插件注入对应的Option
public class Plugin1 : IPlugin
{
public Plugin1(IOptions<Service1Options> options)
{
Service1Options option = options.Value;//11111111
}
}
public class Plugin2 : IPlugin
{
public Plugin2(IOptions<Service2Options> options)
{
Service2Options option = options.Value;//22222222
}
}
如何实现?
插件接口
public interface IPlugin
{ }
插件节点获取器
/// <summary>
/// Plugin配置节点获取器
/// </summary>
/// <typeparam name="TPlugin"></typeparam>
public interface IPluginConfigurationProvider<TPlugin>
{
public IConfiguration Configuration { get; }
}
public class PluginConfigurationProvider<TPlugin> : IPluginConfigurationProvider<TPlugin>
where TPlugin : IPlugin
{
public IConfiguration Configuration { get; set; }
public PluginConfigurationProvider(IConfiguration configuration)
{
string sectionName = typeof(TPlugin).Name;
var section = configuration.GetSection(sectionName);
if (section != null)
{
Configuration = section;
}
}
}
从配置中获取插件设置
/// <summary>
/// 从配置中获取插件设置
/// </summary>
/// <typeparam name="TPlugin">插件类型</typeparam>
/// <typeparam name="TPluginOptions">插件设置</typeparam>
public class PluginConfigrationOptions<TPlugin, TPluginOptions> : ConfigureFromConfigurationOptions<TPluginOptions>
where TPluginOptions : class, new()
{
public PluginConfigrationOptions(IPluginConfigurationProvider<TPlugin> provider) : base(provider.Configuration)
{
}
}
Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddTransient<IConfigureOptions<Service1Options>, PluginConfigrationOptions<Plugin1, Service1Options>>();
services.AddTransient<IConfigureOptions<Service2Options>, PluginConfigrationOptions<Plugin2, Service2Options>>();
services.AddTransient(typeof(IPluginConfigurationProvider<>), typeof(PluginConfigurationProvider<>));
services.AddTransient<Plugin1>();
services.AddTransient<Plugin2>();
var provider = services.BuildServiceProvider();
var service1 = provider.GetRequiredService<Plugin1>();//1111111
var service2 = provider.GetRequiredService<Plugin2>();//2222222
}