.net core 控制檯程式使用依賴注入(Autofac)

just2發表於2018-11-26

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類如下

      

 1 using BackToCOS.IoC;
 2 using log4net;
 3 using Microsoft.Extensions.Configuration;
 4 using Microsoft.Extensions.DependencyInjection;
 5 using Microsoft.Extensions.Logging;
 6 using Myvas.AspNetCore.TencentCos;
 7 using System;
 8 using System.IO;
 9 using Topshelf;
10 
11 namespace BackToCOS
12 {
13     class Program
14     {
15         static void Main(string[] args)
16         {
17             var configuration = new ConfigurationBuilder()
18               .SetBasePath(Directory.GetCurrentDirectory())
19               .AddJsonFile("appsettings.json", true, true)
20               .AddJsonFile("appsettings.Development.json", true, true)
21               .Build();
22             IServiceCollection services = new ServiceCollection();
23           
24             services.AddTencentCos(options =>
25             {
26                 options.SecretId = configuration["TencentCos:SecretId"];
27                 options.SecretKey = configuration["TencentCos:SecretKey"];
28             });
29             services.AddLogging(builder => builder
30                .AddConfiguration(configuration.GetSection("Logging"))
31                .AddConsole());
32             //注入
33             services.AddSingleton<ITencentCosHandler, TencentCosHandler>();
34             //用Autofac接管
35             AutofacContainer.Build(services);
36             log4net.Config.XmlConfigurator.ConfigureAndWatch(LogManager.CreateRepository("NETCoreRepository"), new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
37             HostFactory.Run(x =>
38             {
39                 x.UseLog4Net();
40                 x.Service<BackupServiceRunner>();
41                 x.RunAsLocalSystem();
42                 x.SetDescription("備份到cos的服務");
43                 x.SetDisplayName("備份到cos的服務");
44                 x.SetServiceName("BackToCOS");
45                 x.EnablePauseAndContinue();
46             });
47         }
48     }
49 
50 }

4、用容器獲取事例(非建構函式)

 1 using log4net;
 2 using Microsoft.Extensions.Options;
 3 using Myvas.AspNetCore.TencentCos;
 4 using Quartz;
 5 using System;
 6 using System.Collections.Generic;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 
10 namespace BackToCOS.Jobs
11 {
12     //DisallowConcurrentExecution屬性標記任務不可並行
13     [DisallowConcurrentExecution] 
14     public class BackupJob : IJob
15     {
16         private readonly ILog _log = LogManager.GetLogger("NETCoreRepository", typeof(BackupJob));
17         public Task Execute(IJobExecutionContext context)
18         {
19             try
20             {
21                 _log.Info("測試任務,當前系統時間:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
22                 ITencentCosHandler tencentCosHandler = IoC.AutofacContainer.Resolve<ITencentCosHandler>();
23                 var ss = tencentCosHandler.AllBucketsAsync();
24                 return Task.CompletedTask;
25             }
26             catch (Exception ex)
27             {
28                 JobExecutionException e2 = new JobExecutionException(ex);
29                 _log.Error("測試任務異常", ex);
30             }
31             return Task.CompletedTask;
32         }
33     }
34 }

 

相關文章