自己实现的一个简单的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>();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构