开始之前确保已完成步骤1创建解决方案和类库项目,并在对应项目中安装nuget包
通过Autofac注入.json配置文件,首先在ACD.Domain项目中创建配置文件实体,新建类文件AppSettingConfig.cs
1 2 3 4 5 6 7
|
public class AppSettingConfig { }
|
ACD.Infrastructure项目中创建类文件Startup.cs,实现配置文件的单例注入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public static class Startup { public static async Task<AppSettingConfig> AddAppConfig(this ContainerBuilder builder,string configFileName = "appsettings.json") { var configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFileName);
if (!File.Exists(configFile)) throw new FileNotFoundException($"{configFileName} 配置文件不存在");
string jsonString; using (var stream = File.OpenRead(configFile)) { var reader = new StreamReader(stream); jsonString = await reader.ReadToEndAsync(); }
var appSetting = JsonConvert.DeserializeObject<AppSettingConfig>(jsonString);
builder .RegisterInstance(appSetting) .SingleInstance();
return appSetting; } }
|
ACD.Client项目中添加appsettings.json配置文件
1 2 3
| { //"DbConfig": "123123" }
|
ACD.Client项目中添加类文件AppInit.cs,通过Autofac注入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| internal class AppInit { private static IContainer Container;
internal static async Task Init() { var builder = new ContainerBuilder();
var config = await builder.AddAppConfig("appsettings.json");
Container = builder.Build(); }
internal static T Resolve<T>() => Container.Resolve<T>(); }
|
使用方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
await AppInit.Init();
将AppInit中的内容在Global.asax中或ApplicationStart中实现
AppSettingConfig config = AppInit.Resolve<AppSettingConfig>();
public class ACDesign { private readonly AppSettingConfig _config;
public ACDesign(AppSettingConfig config) => _config = config;
public void Demo() { } }
|