.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 ...
随机推荐
- 【搜索】bzoj3109 [cqoi2013]新数独
搜索,没什么好说的.要注意读入. Code: #include<cstdio> #include<cstdlib> using namespace std; ][]= {{,, ...
- Tomcat上java.lang.IllegalStateException: Optional int parameter 'id' is not present
今日, 本人在tomcat+spring mvc平台的服务器上遇到java.lang.IllegalStateException: Optional int parameter 'id' is not ...
- #Java Web累积#关于MUI的上滑和下拉加载
其实按照MUI的文档去写,也没什么问题: JSP中: <%@ page contentType="text/html;charset=UTF-8" language=&quo ...
- Ubuntu中APache+mod_pyhon
安装apache 1.sudo apt-get install Apache2 Apxs(Apache extension tool既apache扩展模块的工具)的安装: 1.sudo apt-get ...
- 《SQL Server企业级平台管理实践》读书笔记
http://www.cnblogs.com/zhijianliutang/category/277162.html
- Cargo, Rust’s Package Manager
http://doc.crates.io/ Installing The easiest way to get Cargo is to get the current stable release o ...
- 如何ping测有端口的网站
参考:http://jingyan.baidu.com/article/c1a3101e878dcede656deb05.html 参考2:http://www.haoid.cn/post/261 现 ...
- Web API使用记录系列(一)创建API项目与基本配置
本系列文章主要记录Web API使用过程中的一些个人总结,包括创建API项目.基础配置.ApiTestClient使用与HelpPage页面的优化.Owin与OAuth的使用等. 本节主要内容是API ...
- shell中job管理
参考 http://www.cnblogs.com/ggjucheng/archive/2012/10/21/2733028.html 在命令后添加一个&,如firefox &: ...
- JavaScript基础入门教程(一)
本系列教程的说明 本教程说白了可以说是我自己学习JavaScript的笔记,主要内容参考自<JavaScript权威指南>,部分内容可能来自互联网,本系列教程假设学者之前学过c或者其它的编 ...