Autofac-.net core控制檯使用依賴注入【轉】
阿新 • • 發佈:2020-07-06
1、Autofac IOC 容器 ,便於在其他類獲取注入的物件
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Autofac; using Autofac.Core; using Autofac.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection; namespace BackToCOS.IoC { /// <summary> /// Autofac IOC 容器 /// </summary> public class AutofacContainer { private static ContainerBuilder _builder = new ContainerBuilder(); private static IContainer _container; private static string[] _otherAssembly; private static List<Type> _types = new List<Type>(); private static Dictionary<Type, Type> _dicTypes = new Dictionary<Type, Type>(); /// <summary> /// 註冊程式集 /// </summary> /// <param name="assemblies">程式集名稱的集合</param> public static void Register(params string[] assemblies) { _otherAssembly = assemblies; } /// <summary> /// 註冊型別 /// </summary> /// <param name="types"></param> public static void Register(params Type[] types) { _types.AddRange(types.ToList()); } /// <summary> /// 註冊程式集。 /// </summary> /// <param name="implementationAssemblyName"></param> /// <param name="interfaceAssemblyName"></param> public static void Register(string implementationAssemblyName, string interfaceAssemblyName) { var implementationAssembly = Assembly.Load(implementationAssemblyName); var interfaceAssembly = Assembly.Load(interfaceAssemblyName); var implementationTypes = implementationAssembly.DefinedTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsGenericType && !t.IsNested); foreach (var type in implementationTypes) { var interfaceTypeName = interfaceAssemblyName + ".I" + type.Name; var interfaceType = interfaceAssembly.GetType(interfaceTypeName); if (interfaceType.IsAssignableFrom(type)) { _dicTypes.Add(interfaceType, type); } } } /// <summary> /// 註冊 /// </summary> /// <typeparam name="TInterface"></typeparam> /// <typeparam name="TImplementation"></typeparam> public static void Register<TInterface, TImplementation>() where TImplementation : TInterface { _dicTypes.Add(typeof(TInterface), typeof(TImplementation)); } /// <summary> /// 註冊一個單例實體 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance"></param> public static void Register<T>(T instance) where T:class { _builder.RegisterInstance(instance).SingleInstance(); } /// <summary> /// 構建IOC容器 /// </summary> public static IServiceProvider Build(IServiceCollection services) { if (_otherAssembly != null) { foreach (var item in _otherAssembly) { _builder.RegisterAssemblyTypes(Assembly.Load(item)); } } if (_types != null) { foreach (var type in _types) { _builder.RegisterType(type); } } if (_dicTypes != null) { foreach (var dicType in _dicTypes) { _builder.RegisterType(dicType.Value).As(dicType.Key); } } _builder.Populate(services); _container = _builder.Build(); return new AutofacServiceProvider(_container); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T Resolve<T>() { return _container.Resolve<T>(); } public static T Resolve<T>(params Parameter[] parameters) { return _container.Resolve<T>(parameters); } public static object Resolve(Type targetType) { return _container.Resolve(targetType); } public static object Resolve(Type targetType, params Parameter[] parameters) { return _container.Resolve(targetType, parameters); } } }
2、用nuget安裝
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
3、Program類如下
using BackToCOS.IoC; using log4net; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Myvas.AspNetCore.TencentCos; using System; using System.IO; using Topshelf; namespace BackToCOS { class Program { static void Main(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", true, true) .AddJsonFile("appsettings.Development.json", true, true) .Build(); IServiceCollection services = new ServiceCollection(); services.AddTencentCos(options => { options.SecretId = configuration["TencentCos:SecretId"]; options.SecretKey = configuration["TencentCos:SecretKey"]; }); services.AddLogging(builder => builder .AddConfiguration(configuration.GetSection("Logging")) .AddConsole()); //注入 services.AddSingleton<ITencentCosHandler, TencentCosHandler>(); //用Autofac接管 AutofacContainer.Build(services); log4net.Config.XmlConfigurator.ConfigureAndWatch(LogManager.CreateRepository("NETCoreRepository"), new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config")); HostFactory.Run(x => { x.UseLog4Net(); x.Service<BackupServiceRunner>(); x.RunAsLocalSystem(); x.SetDescription("備份到cos的服務"); x.SetDisplayName("備份到cos的服務"); x.SetServiceName("BackToCOS"); x.EnablePauseAndContinue(); }); } } }
4、用容器獲取事例(非建構函式)
using log4net; using Microsoft.Extensions.Options; using Myvas.AspNetCore.TencentCos; using Quartz; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace BackToCOS.Jobs { //DisallowConcurrentExecution屬性標記任務不可並行 [DisallowConcurrentExecution] public class BackupJob : IJob { private readonly ILog _log = LogManager.GetLogger("NETCoreRepository", typeof(BackupJob)); public Task Execute(IJobExecutionContext context) { try { _log.Info("測試任務,當前系統時間:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); ITencentCosHandler tencentCosHandler = IoC.AutofacContainer.Resolve<ITencentCosHandler>(); var ss = tencentCosHandler.AllBucketsAsync(); return Task.CompletedTask; } catch (Exception ex) { JobExecutionException e2 = new JobExecutionException(ex); _log.Error("測試任務異常", ex); } return Task.CompletedTask; } } }