C# 加载配置文件
//加载配置文件 var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); ConfigurationManager.Configuration = builder.Build(); #region 反射加载程序集dll到运行时,.net core 2.0不支持引用第三方DLL直接加载 TODO 升级2.0.3 或者Nuget加载 Assembly entry = Assembly.GetEntryAssembly(); string dir = Path.GetDirectoryName(entry.Location); var dllPath = dir + "\\MongoRepository.Net45.dll"; AssemblyLoadContext.Default.LoadFromAssemblyPath(dllPath); #endregion
//注册IOC=Autofac 类 public class IocManager { private static ILifetimeScope _container; public static void Initialize(params string[] assemblyNamePattens) { ContainerBuilder builder = new ContainerBuilder(); _container = builder.Build(); Initialize(_container, assemblyNamePattens); } public static void Initialize(ILifetimeScope container, params string[] assemblyNamePattens) { container.Update(builder => { //运行绝对路径=AppDomain.CurrentDomain.BaseDirectory Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll") .Where(it => Regex.IsMatch(it, $@"(OA|{assemblyNamePattens.Join("|")})\.[^\\]*\.dll")) .Each(it => AppDomain.CurrentDomain.Load(Path.GetFileNameWithoutExtension(it))); //注册IOC var assembiles = AppDomain.CurrentDomain.GetAssemblies(); //组件筛选使用 /* var assembiles = AppDomain.CurrentDomain.GetAssemblies()//GetReferencingAssemblies() .Where(it => Regex.IsMatch(Path.GetFileNameWithoutExtension(it.Location) + ".dll", $@"(OA|{assemblyNamePattens.Join("|")})\.[^\\]*\.dll")).ToArray(); */ builder.RegisterAssemblyTypes(assembiles) .Except<IDependencySingleton>() .Except<IDependencyRequestSingleton>() .As<IDependency>().AsSelf().AsImplementedInterfaces(); builder.RegisterAssemblyTypes(assembiles) .Except<IDependencyRequestSingleton>() .As<IDependencySingleton>().AsSelf().AsImplementedInterfaces().SingleInstance(); builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()) .As<IDependencyRequestSingleton>().AsSelf().AsImplementedInterfaces() .InstancePerLifetimeScope(); }); } public static ILifetimeScope GetContainer() { return _container; } public static void SetContainer(ILifetimeScope container) { _container = container; } }