40 lines
1.5 KiB
C#
40 lines
1.5 KiB
C#
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Hosting;
|
|
|
|
namespace MAX.Plugins;
|
|
|
|
/// <summary>插件独立配置,不合并宿主或其他插件配置。</summary>
|
|
public sealed class PluginContext : IDisposable
|
|
{
|
|
private int disposed;
|
|
public string Id { get; }
|
|
public string DirectoryPath { get; }
|
|
public IHostEnvironment Environment { get; }
|
|
public IConfigurationRoot Configuration { get; }
|
|
|
|
public PluginContext(string id, string directoryPath, IHostEnvironment environment)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(id);
|
|
ArgumentNullException.ThrowIfNull(environment);
|
|
Id = id;
|
|
DirectoryPath = Path.GetFullPath(directoryPath);
|
|
Environment = environment;
|
|
Configuration = new ConfigurationBuilder()
|
|
.SetBasePath(DirectoryPath)
|
|
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
|
|
.AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true, reloadOnChange: false)
|
|
.AddEnvironmentVariables($"Plugins__{id}__")
|
|
.Build();
|
|
}
|
|
|
|
public string RequireConfiguration(string key) =>
|
|
!string.IsNullOrWhiteSpace(Configuration[key]) ? Configuration[key]!
|
|
: throw new InvalidOperationException($"插件 {Id} 缺少配置 {key},请检查 {Path.Combine(DirectoryPath, "appsettings.json")}。");
|
|
|
|
public void Dispose()
|
|
{
|
|
if (Interlocked.Exchange(ref disposed, 1) == 0)
|
|
(Configuration as IDisposable)?.Dispose();
|
|
}
|
|
}
|