.net core 控制台程序使用依赖注入(Autofac)
程序员文章站
2022-04-28 21:48:52
1、Autofac IOC 容器 ,便于在其他类获取注入的对象 2、用nuget安装 using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; 3、Program类如下 4、用容 ......
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类如下
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 WebApi——依赖注入Autofac
-
ASP.NET Core 2.2 WebApi 系列【三】AutoFac 仓储接口的依赖注入
-
.net core控制台程序中使用原生依赖注入
-
.NET Core使用命令行参数库构建控制台应用程序
-
ASP.NET Core - 在ActionFilter中使用依赖注入
-
【半小时大话.net依赖注入】(一)理论基础+实战控制台程序实现AutoFac注入
-
.NET Core控制台应用程序如何使用异步(Async)Main方法详解
-
ASP.NET Core 过滤器中使用依赖注入知识点总结
-
.net core 控制台程序使用依赖注入(Autofac)
-
【半小时大话.net依赖注入】(下)详解AutoFac+实战Mvc、Api以及.NET Core的依赖注入