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)的更多相关文章

  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. python基础之封装与绑定方法

    封装 1.什么是封装: 封:属性对外隐藏,但对内开放 装:申请一个名称空间,往里装入一系列名字/属性 2.为什么要封装: 封装数据属性:不让外部使用者直接使用数据,需要类内部开辟一个接口,让外部通过接 ...

  2. Problem D: 零起点学算法83——数组中删数

    #include<stdio.h> int main(void) { int n,i,t,x,flag; while(scanf("%d",&n)!=EOF) ...

  3. Problem B: 查找某一个数

    #include<stdio.h> int main(void) { ]; int i; char ch='n'; while(scanf("%d %d",&x ...

  4. leetcode 576. Out of Boundary Paths

    leetcode 576 题意大概就是在一个m*n的网格中,在坐标为[i,j]的网格上放一个物体,在规定时间N(t<=N)中,有多少种方法把物体移动出去.物体只能上下左右移动,一次移动一格,移动 ...

  5. sqlite 增加字段语句

    ALTER TABLE `table1` ADD `AAAA` VARCHAR( 10 ) NOT NULL ; ALTER TABLE 'IPC_FGUID' ADD 'iPassageway' V ...

  6. subline text 常用插件

    C语言 Alignment   c Improved   cool format doc Blocker   cTags   AllAutoComplete       wakatime 精确统计你再 ...

  7. wince5.0 plat form builder下载

    学习嵌入式开发的朋友都知道,嵌入式开发主要用到2个软件一个是Platform Builder for Windows CE 5.0一个是VS.NET2005,其中VS.NET2005网上很容易下载,现 ...

  8. ImageWriter制作ubuntu的U盘启动盘

    转自:http://my.oschina.net/f839903061/blog/197935?p={{currentPage+1}} 1.工具从ubuntn中文网中下载指定软件:ImageWrite ...

  9. hive如何使用中文查询条件

    直接在hql中使用中文会报错:org.apache.hadoop.ipc.RemoteException: java.io.IOException: java.lang.RuntimeExceptio ...

  10. OpenCV图像金字塔

    图像金字塔 目标 本文档尝试解答如下问题: 如何使用OpenCV函数 pyrUp 和 pyrDown 对图像进行向上和向下采样. 原理 Note 以下内容来自于Bradski和Kaehler的大作:  ...