zoukankan      html  css  js  c++  java
  • Autofac-.net core控制台使用依赖注入【转】

    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;
            }
        }
    }
    
  • 相关阅读:
    Linux 安装jdk 报错 Error: could not find libjava.so Error: Could not find Java SE Runtime Environment.
    k8s 挂载ceph rbd
    spinnaker结合表达式实现发版时下拉列表选择docker image
    istio环境集成zipkin
    istio 日志打印 request body 和respon body
    jenkins任务中无法执行sudo,管理员操作
    ansible根据shell命令返回值,判断是否应该急继续往下执行
    ReplicaSetController、ReplicationController
    kubeproxy
    PodGCController
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/13254278.html
Copyright © 2011-2022 走看看