1、Autofac IOC 容器 ,便于在其他类获取注入的对象

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using Autofac;
  6. using Autofac.Core;
  7. using Autofac.Extensions.DependencyInjection;
  8. using Microsoft.Extensions.DependencyInjection;
  9.  
  10. namespace BackToCOS.IoC
  11. {
  12. /// <summary>
  13. /// Autofac IOC 容器
  14. /// </summary>
  15. public class AutofacContainer
  16. {
  17. private static ContainerBuilder _builder = new ContainerBuilder();
  18. private static IContainer _container;
  19. private static string[] _otherAssembly;
  20. private static List<Type> _types = new List<Type>();
  21. private static Dictionary<Type, Type> _dicTypes = new Dictionary<Type, Type>();
  22.  
  23. /// <summary>
  24. /// 注册程序集
  25. /// </summary>
  26. /// <param name="assemblies">程序集名称的集合</param>
  27. public static void Register(params string[] assemblies)
  28. {
  29. _otherAssembly = assemblies;
  30. }
  31.  
  32. /// <summary>
  33. /// 注册类型
  34. /// </summary>
  35. /// <param name="types"></param>
  36. public static void Register(params Type[] types)
  37. {
  38. _types.AddRange(types.ToList());
  39. }
  40. /// <summary>
  41. /// 注册程序集。
  42. /// </summary>
  43. /// <param name="implementationAssemblyName"></param>
  44. /// <param name="interfaceAssemblyName"></param>
  45. public static void Register(string implementationAssemblyName, string interfaceAssemblyName)
  46. {
  47. var implementationAssembly = Assembly.Load(implementationAssemblyName);
  48. var interfaceAssembly = Assembly.Load(interfaceAssemblyName);
  49. var implementationTypes =
  50. implementationAssembly.DefinedTypes.Where(t =>
  51. t.IsClass && !t.IsAbstract && !t.IsGenericType && !t.IsNested);
  52. foreach (var type in implementationTypes)
  53. {
  54. var interfaceTypeName = interfaceAssemblyName + ".I" + type.Name;
  55. var interfaceType = interfaceAssembly.GetType(interfaceTypeName);
  56. if (interfaceType.IsAssignableFrom(type))
  57. {
  58. _dicTypes.Add(interfaceType, type);
  59. }
  60. }
  61. }
  62. /// <summary>
  63. /// 注册
  64. /// </summary>
  65. /// <typeparam name="TInterface"></typeparam>
  66. /// <typeparam name="TImplementation"></typeparam>
  67. public static void Register<TInterface, TImplementation>() where TImplementation : TInterface
  68. {
  69. _dicTypes.Add(typeof(TInterface), typeof(TImplementation));
  70. }
  71.  
  72. /// <summary>
  73. /// 注册一个单例实体
  74. /// </summary>
  75. /// <typeparam name="T"></typeparam>
  76. /// <param name="instance"></param>
  77. public static void Register<T>(T instance) where T:class
  78. {
  79. _builder.RegisterInstance(instance).SingleInstance();
  80. }
  81.  
  82. /// <summary>
  83. /// 构建IOC容器
  84. /// </summary>
  85. public static IServiceProvider Build(IServiceCollection services)
  86. {
  87. if (_otherAssembly != null)
  88. {
  89. foreach (var item in _otherAssembly)
  90. {
  91. _builder.RegisterAssemblyTypes(Assembly.Load(item));
  92. }
  93. }
  94.  
  95. if (_types != null)
  96. {
  97. foreach (var type in _types)
  98. {
  99. _builder.RegisterType(type);
  100. }
  101. }
  102.  
  103. if (_dicTypes != null)
  104. {
  105. foreach (var dicType in _dicTypes)
  106. {
  107. _builder.RegisterType(dicType.Value).As(dicType.Key);
  108. }
  109. }
  110.  
  111. _builder.Populate(services);
  112. _container = _builder.Build();
  113. return new AutofacServiceProvider(_container);
  114. }
  115.  
  116. /// <summary>
  117. ///
  118. /// </summary>
  119. /// <typeparam name="T"></typeparam>
  120. /// <returns></returns>
  121. public static T Resolve<T>()
  122. {
  123. return _container.Resolve<T>();
  124. }
  125.  
  126. public static T Resolve<T>(params Parameter[] parameters)
  127. {
  128. return _container.Resolve<T>(parameters);
  129. }
  130.  
  131. public static object Resolve(Type targetType)
  132. {
  133. return _container.Resolve(targetType);
  134. }
  135.  
  136. public static object Resolve(Type targetType, params Parameter[] parameters)
  137. {
  138. return _container.Resolve(targetType, parameters);
  139. }
  140. }
  141. }

  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. }

.net core 控制台程序使用依赖注入(Autofac)的更多相关文章

  1. 大比速:remoting、WCF(http)、WCF(tcp)、WCF(RESTful)、asp.net core(RESTful) .net core 控制台程序使用依赖注入(Autofac)

    大比速:remoting.WCF(http).WCF(tcp).WCF(RESTful).asp.net core(RESTful) 近来在考虑一个服务选型,dotnet提供了众多的远程服务形式.在只 ...

  2. 如何在.NET Core控制台程序中使用依赖注入

    背景介绍 依赖注入(Dependency Injection), 是面向对象编程中的一种设计原则,可以用来减低代码之间的耦合度.在.NET Core MVC中 我们可以在Startup.cs文件的Co ...

  3. 在.NET Core控制台程序中使用依赖注入

    之前都是在ASP.NET Core中使用依赖注入(Dependency Injection),昨天遇到一个场景需要在.NET Core控制台程序中使用依赖注入,由于对.NET Core中的依赖注入机制 ...

  4. .Net Core控制台应用程序使用依赖注入、配置文件等

    .Net Core作为一门新语言,资料实在是太少了,并且国内学习的人也不多,虽然性能还行也跨平台了但是生态圈不发展起来也不行 刚出来的时候用 .Net Core + Dapper + Mysql 弄了 ...

  5. .net core 依赖注入, autofac 简单使用

    综述 ASP.NET Core  支持依赖注入, 也推荐使用依赖注入. 主要作用是用来降低代码之间的耦合度. 什么是控制反转? 控制反转(Inversion of Control,缩写为IoC),是面 ...

  6. NET Core 控制台程序读 appsettings.json 、注依赖、配日志、设 IOptions

    .NET Core 控制台程序没有 ASP.NET Core 的 IWebHostBuilder 与 Startup.cs ,那要读 appsettings.json.注依赖.配日志.设 IOptio ...

  7. ASP.NET Core中如影随形的”依赖注入”[下]: 历数依赖注入的N种玩法

    在对ASP.NET Core管道中关于依赖注入的两个核心对象(ServiceCollection和ServiceProvider)有了足够的认识之后,我们将关注的目光转移到编程层面.在ASP.NET ...

  8. [ASP.NET Core 3框架揭秘] 依赖注入[5]: 利用容器提供服务

    毫不夸张地说,整个ASP.NET Core框架是建立在依赖注入框架之上的.ASP.NET Core应用在启动时构建管道以及利用该管道处理每个请求过程中使用到的服务对象均来源于依赖注入容器.该依赖注入容 ...

  9. [ASP.NET Core 3框架揭秘] 依赖注入[7]:服务消费

    包含服务注册信息的IServiceCollection集合最终被用来创建作为依赖注入容器的IServiceProvider对象.当需要消费某个服务实例的时候,我们只需要指定服务类型调用IService ...

随机推荐

  1. Java并发(五):synchronized实现原理

    一.synchronized用法 Java中的同步块用synchronized标记. 同步块在Java中是同步在某个对象上(监视器对象). 所有同步在一个对象上的同步块在同时只能被一个线程进入并执行操 ...

  2. JVM命令-java服务器故障排查

    一.top(Linux命令) 执行top命令:    (查看进程15477的详细情况,下文用到) 系统信息(前五行): 第1行:Top 任务队列信息(系统运行状态及平均负载),与uptime命令结果相 ...

  3. Java学习笔记(15)

    iterator方法 迭代器的作用:就是用于抓取集合中的元素 注:迭代器返回的一个接口类型的实现类,是一种多态的用法,而不是接口在调用方法 public class Demo2 { public st ...

  4. TCP连接 断开

     参考:http://blog.csdn.net/cyberhero/article/details/5827181 1.建立连接协议 (三次握手)      (1)客户端发送一个带SYN标志的TCP ...

  5. 基于tiny4412的Linux内核移植(支持device tree)(一)

    作者信息 作者: 彭东林 邮箱:pengdonglin137@163.com QQ:405728433 平台简介 开发板:tiny4412ADK + S700 + 4GB Flash 要移植的内核版本 ...

  6. 【spring cloud】spring cloud中启动eureka集群时候,发生端口已经绑定的报错The Tomcat connector configured to listen on port 8000 failed to start. The port may already be in use or the connector may be misconfigured.

    在分别设置 进行微服务eureka集群启动时候,执行命令行启动jar包时候,报错前面一个端口8000已经被使用,而我这里启动的配置文件中端口号是8001,怎么会导致端口冲突呢?? 但是报错我的端口冲突 ...

  7. 常见Linux版本

      一 常见Linux版本 website feature description http://www.ubuntu.com/ 当前最流行 Ubuntu 正是基于 Debian 之上,旨在创建一个可 ...

  8. CDHtmlDialog 基本使用

    跳转 Navigate("res://tt.exe/#138"); 138是html的资源号 输入框的Get,set HRESULT CTTDlg::OnButtonCancel( ...

  9. postgres--vacuum

    vacuum的功能 回收空间 数据库总是不断地在执行删除,更新等操作.良好的空间管理非常重要,能够对性能带来大幅提高. postgresql中执行delete操作后,表中的记录只是被标示为删除状态,并 ...

  10. 关于TagHelper的那些事情——如何自定义TagHelper(TagHelper基类)

    写在开头 前面介绍了TagHelper的基本概念和内嵌的TagHelpers,想必大家对TagHelper都有一定的了解.TagHelper看上去有点像WebControl,但它不同于WebContr ...