
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 BackToCOS12 {13 class Program14 {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)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 => builder30 .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.Jobs11 {12 //disallowConcurrentExecution属性标记任务不可并行13 [disallowConcurrentExecution] 14 public class BackupJob : IJob15 {16 private Readonly ILog _log = LogManager.GetLogger("NETCoreRepository",typeof(BackupJob));17 public Task Execute(IJobExecutionContext context)18 {19 try20 {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)全部内容,希望文章能够帮你解决.net core 控制台程序使用依赖注入(Autofac)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)