-
自己实现的一个简单的C# IOC 容器
IService接口,以实现服务的启动、停止功能:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Utils { /// <summary> /// 服务接口 /// </summary> public interface IService { /// <summary> /// 服务启动 /// </summary> void OnStart(); /// <summary> /// 服务停止 /// </summary> void OnStop(); } }
AbstractService服务抽象类:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Utils { /// <summary> /// 服务抽象类 /// </summary> public abstract class AbstractService : IService { /// <summary> /// 服务启动 /// </summary> public virtual void OnStart() { } /// <summary> /// 服务停止 /// </summary> public virtual void OnStop() { } } }
IOC容器帮助类:

using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Web; namespace Utils { /// <summary> /// 服务帮助类 /// </summary> public partial class ServiceHelper { #region 变量 /// <summary> /// 接口的对象集合 /// </summary> private static ConcurrentDictionary<Type, object> _dict = new ConcurrentDictionary<Type, object>(); #endregion #region Get 获取实例 /// <summary> /// 获取实例 /// </summary> public static T Get<T>() { Type type = typeof(T); object obj = _dict.GetOrAdd(type, key => Activator.CreateInstance(type)); return (T)obj; } #endregion #region Get 通过Func获取实例 /// <summary> /// 获取实例 /// </summary> public static T Get<T>(Func<T> func) { Type type = typeof(T); object obj = _dict.GetOrAdd(type, (key) => func()); return (T)obj; } #endregion #region RegisterAssembly 注册程序集 /// <summary> /// 注册程序集 /// </summary> /// <param name="type">程序集中的一个类型</param> public static void RegisterAssembly(Type type) { RegisterAssembly(Assembly.GetAssembly(type).FullName); } /// <summary> /// 注册程序集 /// </summary> /// <param name="assemblyString">程序集名称的长格式</param> public static void RegisterAssembly(string assemblyString) { LogTimeUtil logTimeUtil = new LogTimeUtil(); Assembly assembly = Assembly.Load(assemblyString); Type[] typeArr = assembly.GetTypes(); string iServiceInterfaceName = typeof(IService).FullName; foreach (Type type in typeArr) { Type typeIService = type.GetInterface(iServiceInterfaceName); if (typeIService != null && !type.IsAbstract) { Type[] interfaceTypeArr = type.GetInterfaces(); object obj = Activator.CreateInstance(type); _dict.GetOrAdd(type, obj); foreach (Type interfaceType in interfaceTypeArr) { if (interfaceType != typeof(IService)) { _dict.GetOrAdd(interfaceType, obj); } } } } logTimeUtil.LogTime("ServiceHelper.RegisterAssembly 注册程序集 " + assemblyString + " 耗时"); } #endregion #region 启动所有服务 /// <summary> /// 启动所有服务 /// </summary> public static Task StartAllService() { return Task.Run(() => { List<Task> taskList = new List<Task>(); foreach (object o in _dict.Values.Distinct()) { Task task = Task.Factory.StartNew(obj => { IService service = obj as IService; try { service.OnStart(); LogUtil.Log("服务 " + obj.GetType().FullName + " 已启动"); } catch (Exception ex) { LogUtil.Error(ex, "服务 " + obj.GetType().FullName + " 启动失败"); } }, o); taskList.Add(task); } Task.WaitAll(taskList.ToArray()); }); } #endregion #region 停止所有服务 /// <summary> /// 停止所有服务 /// </summary> public static Task StopAllService() { return Task.Run(() => { List<Task> taskList = new List<Task>(); Type iServiceInterfaceType = typeof(IService); foreach (object o in _dict.Values.Distinct()) { Task task = Task.Factory.StartNew(obj => { if (iServiceInterfaceType.IsAssignableFrom(obj.GetType())) { IService service = obj as IService; try { service.OnStop(); LogUtil.Log("服务 " + obj.GetType().FullName + " 已停止").Wait(); } catch (Exception ex) { LogUtil.Error(ex, "服务 " + obj.GetType().FullName + " 停止失败").Wait(); } } }, o); taskList.Add(task); } Task.WaitAll(taskList.ToArray()); }); } #endregion } }
说明:
RegisterAssembly方法:注册实现类,只要程序集中的类实现了某个接口,就注册,把它的类型以及接口的类型作为Key添加到字典中,以接口类型作为Key的时候,过滤掉IService这个接口。
StartAllService方法:调用所有服务的OnStart方法。
StopAllService方法:调用所有服务的OnStop方法。
如何使用:
服务的注册与启动:

ServiceHelper.RegisterAssembly(typeof(MyActionFilter)); ServiceHelper.StartAllService().Wait();
说明:RegisterAssembly方法的参数,传递程序集中任何一个类型即可。
服务的停止:

ServiceHelper.StopAllService().Wait();
服务的定义:

using Models; using Newtonsoft.Json; using NetWebApi.DAL; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Timers; using System.Web; using System.Collections.Concurrent; using Utils; using System.Configuration; namespace NetWebApi.BLL { /// <summary> /// 通用 /// </summary> public class CommonBll : AbstractService { #region OnStart 服务启动 /// <summary> /// 服务启动 /// </summary> public override void OnStart() { } #endregion #region OnStop 服务停止 /// <summary> /// 服务停止 /// </summary> public override void OnStop() { } #endregion } }
调用服务:

CommonBll commonBll = ServiceHelper.Get<CommonBll>();
临时注册并调用服务:

SaveDataBll m_SaveDataBll = ServiceHelper.Get<SaveDataBll>();
出处:https://www.cnblogs.com/s0611163/p/15166869.html
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
SQL Server -- 解决存储过程传入参数作为s
关于JS定时器的整理
JS中使用Promise.all控制所有的异步请求都完
js中字符串的方法
import-local执行流程与node模块路径解析流程
检测数据类型的四种方法
js中数组的方法,32种方法
前端操作方法
数据类型
window.localStorage.setItem 和 localStorage.setIte
如何完美解决前端数字计算精度丢失与数