.net core 控制台程序使用依赖注入(Autofac)
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;
- }
- }
- }
.net core 控制台程序使用依赖注入(Autofac)的更多相关文章
- 大比速: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提供了众多的远程服务形式.在只 ...
- 如何在.NET Core控制台程序中使用依赖注入
背景介绍 依赖注入(Dependency Injection), 是面向对象编程中的一种设计原则,可以用来减低代码之间的耦合度.在.NET Core MVC中 我们可以在Startup.cs文件的Co ...
- 在.NET Core控制台程序中使用依赖注入
之前都是在ASP.NET Core中使用依赖注入(Dependency Injection),昨天遇到一个场景需要在.NET Core控制台程序中使用依赖注入,由于对.NET Core中的依赖注入机制 ...
- .Net Core控制台应用程序使用依赖注入、配置文件等
.Net Core作为一门新语言,资料实在是太少了,并且国内学习的人也不多,虽然性能还行也跨平台了但是生态圈不发展起来也不行 刚出来的时候用 .Net Core + Dapper + Mysql 弄了 ...
- .net core 依赖注入, autofac 简单使用
综述 ASP.NET Core 支持依赖注入, 也推荐使用依赖注入. 主要作用是用来降低代码之间的耦合度. 什么是控制反转? 控制反转(Inversion of Control,缩写为IoC),是面 ...
- NET Core 控制台程序读 appsettings.json 、注依赖、配日志、设 IOptions
.NET Core 控制台程序没有 ASP.NET Core 的 IWebHostBuilder 与 Startup.cs ,那要读 appsettings.json.注依赖.配日志.设 IOptio ...
- ASP.NET Core中如影随形的”依赖注入”[下]: 历数依赖注入的N种玩法
在对ASP.NET Core管道中关于依赖注入的两个核心对象(ServiceCollection和ServiceProvider)有了足够的认识之后,我们将关注的目光转移到编程层面.在ASP.NET ...
- [ASP.NET Core 3框架揭秘] 依赖注入[5]: 利用容器提供服务
毫不夸张地说,整个ASP.NET Core框架是建立在依赖注入框架之上的.ASP.NET Core应用在启动时构建管道以及利用该管道处理每个请求过程中使用到的服务对象均来源于依赖注入容器.该依赖注入容 ...
- [ASP.NET Core 3框架揭秘] 依赖注入[7]:服务消费
包含服务注册信息的IServiceCollection集合最终被用来创建作为依赖注入容器的IServiceProvider对象.当需要消费某个服务实例的时候,我们只需要指定服务类型调用IService ...
随机推荐
- Java并发(五):synchronized实现原理
一.synchronized用法 Java中的同步块用synchronized标记. 同步块在Java中是同步在某个对象上(监视器对象). 所有同步在一个对象上的同步块在同时只能被一个线程进入并执行操 ...
- JVM命令-java服务器故障排查
一.top(Linux命令) 执行top命令: (查看进程15477的详细情况,下文用到) 系统信息(前五行): 第1行:Top 任务队列信息(系统运行状态及平均负载),与uptime命令结果相 ...
- Java学习笔记(15)
iterator方法 迭代器的作用:就是用于抓取集合中的元素 注:迭代器返回的一个接口类型的实现类,是一种多态的用法,而不是接口在调用方法 public class Demo2 { public st ...
- TCP连接 断开
参考:http://blog.csdn.net/cyberhero/article/details/5827181 1.建立连接协议 (三次握手) (1)客户端发送一个带SYN标志的TCP ...
- 基于tiny4412的Linux内核移植(支持device tree)(一)
作者信息 作者: 彭东林 邮箱:pengdonglin137@163.com QQ:405728433 平台简介 开发板:tiny4412ADK + S700 + 4GB Flash 要移植的内核版本 ...
- 【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,怎么会导致端口冲突呢?? 但是报错我的端口冲突 ...
- 常见Linux版本
一 常见Linux版本 website feature description http://www.ubuntu.com/ 当前最流行 Ubuntu 正是基于 Debian 之上,旨在创建一个可 ...
- CDHtmlDialog 基本使用
跳转 Navigate("res://tt.exe/#138"); 138是html的资源号 输入框的Get,set HRESULT CTTDlg::OnButtonCancel( ...
- postgres--vacuum
vacuum的功能 回收空间 数据库总是不断地在执行删除,更新等操作.良好的空间管理非常重要,能够对性能带来大幅提高. postgresql中执行delete操作后,表中的记录只是被标示为删除状态,并 ...
- 关于TagHelper的那些事情——如何自定义TagHelper(TagHelper基类)
写在开头 前面介绍了TagHelper的基本概念和内嵌的TagHelpers,想必大家对TagHelper都有一定的了解.TagHelper看上去有点像WebControl,但它不同于WebContr ...