C#自定义应用程序上下文对象+IOC自己实现依赖注入
以前的好多代码都丢失了,加上最近时间空一些,于是想起整理一下以前的个人半拉子项目,试试让它们重生。自从养成了架构师视觉 搭建框架之后,越来 越看不上以前搭的框架了。先撸个上下文对象加上实现依赖注入。由于还是要依赖.net 4,所以像Autofac这样的就用不了,于是仿照着实现了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | /// <summary> /// 自定义应用程序上下文对象 /// </summary> public class AppContextExt : IDisposable { /// <summary> /// app.config读取 /// </summary> public Configuration AppConfig { get ; set ; } /// <summary> /// 真正的ApplicationContext对象 /// </summary> public ApplicationContext Application_Context { get ; set ; } //服务集合 public static Dictionary<Type, object > Services = new Dictionary<Type, object >(); //服务订阅事件集合 public static Dictionary<Type, IList<Action< object >>> ServiceEvents = new Dictionary<Type, IList<Action< object >>>(); //上下文对象的单例 private static AppContextExt _ServiceContext = null ; private readonly static object lockObj = new object (); /// <summary> /// 禁止外部进行实例化 /// </summary> private AppContextExt() { } /// <summary> /// 获取唯一实例,双锁定防止多线程并发时重复创建实例 /// </summary> /// <returns></returns> public static AppContextExt GetInstance() { if (_ServiceContext == null ) { lock (lockObj) { if (_ServiceContext == null ) { _ServiceContext = new AppContextExt(); } } } return _ServiceContext; } /// <summary> /// 注入Service到上下文 /// </summary> /// <typeparam name="T">接口对象</typeparam> /// <param name="t">Service对象</param> /// <param name="servicesChangeEvent">服务实例更新时订阅的消息</param> public static void RegisterService<T>(T t, Action< object > servicesChangeEvent = null ) where T : class { if (t == null ) { throw new Exception( string .Format( "未将对象实例化,对象名:{0}." , typeof (T).Name)); } if (!Services.ContainsKey( typeof (T))) { try { Services.Add( typeof (T), t); if (servicesChangeEvent != null ) { var eventList = new List<Action< object >>(); eventList.Add(servicesChangeEvent); ServiceEvents.Add( typeof (T), eventList); } } catch (Exception ex) { throw ex; } } if (!Services.ContainsKey( typeof (T))) { throw new Exception( string .Format( "注册Service失败,对象名:{0}." , typeof (T).Name)); } } /// <summary> /// 动态注入dll中的多个服务对象 /// </summary> /// <param name="serviceRuntime"></param> public static void RegisterAssemblyServices( string serviceRuntime) { if (serviceRuntime.IndexOf( ".dll" ) != -1 && !File.Exists(serviceRuntime)) throw new Exception( string .Format( "类库{0}不存在!" , serviceRuntime)); try { Assembly asb = Assembly.LoadFrom(serviceRuntime); var serviceList = asb.GetTypes().Where(t => t.GetCustomAttributes( typeof (ExportAttribute), false ).Any()).ToList(); if (serviceList != null && serviceList.Count > 0) { foreach ( var service in serviceList) { var ifc = ((ExportAttribute)service.GetCustomAttributes( typeof (ExportAttribute), false ).FirstOrDefault()).ContractType; //使用默认的构造函数实例化 var serviceObject = Activator.CreateInstance(service, null ); if (serviceObject != null ) Services.Add(ifc, serviceObject); else throw new Exception( string .Format( "实例化对象{0}失败!" , service)); } } else { throw new Exception( string .Format( "类库{0}里没有Export的Service!" , serviceRuntime)); } } catch (Exception ex) { throw ex; } } /// <summary> /// 获取Service的实例 /// </summary> /// <typeparam name="T">接口对象</typeparam> /// <returns></returns> public static T Resolve<T>() { if (Services.ContainsKey( typeof (T))) return (T)Services[ typeof (T)]; return default (T); } /// <summary> /// 重置Service对象,实现热更新 /// </summary> /// <typeparam name="T">接口对象</typeparam> /// <param name="t">新的服务对象实例</param> public static void ReLoadService<T>(T t) { if (t == null ) { throw new Exception( string .Format( "未将对象实例化,对象名:{0}." , typeof (T).Name)); } if (Services.ContainsKey( typeof (T))) { try { Services[ typeof (T)] = t; if (ServiceEvents.ContainsKey( typeof (T))) { var eventList = ServiceEvents[ typeof (T)]; foreach ( var act in eventList) { act.Invoke(t); } } } catch (Exception ex) { throw ex; } } else if (!Services.ContainsKey( typeof (T))) { throw new Exception( string .Format( "Service实例不存在!对象名:{0}." , typeof (T).Name)); } } /// <summary> /// 激活上下文 /// </summary> public void Start() { GetInstance(); } /// <summary> /// 激活上下文 /// </summary> /// <param name="appContext">真正的ApplicationContext对象</param> public void Start(ApplicationContext appContext) { Application_Context = appContext; GetInstance(); } /// <summary> /// 激活上下文 /// </summary> /// <param name="config">Configuration</param> public void Start(Configuration config) { AppConfig = config; GetInstance(); } /// <summary> /// 激活上下文 /// </summary> /// <param name="appContext">真正的ApplicationContext对象</param> /// <param name="config">Configuration</param> public void Start(ApplicationContext appContext, Configuration config) { AppConfig = config; Application_Context = appContext; GetInstance(); } /// <summary> /// Using支持 /// </summary> public void Dispose() { Services.Clear(); ServiceEvents.Clear(); if (Application_Context != null ) { Application_Context.ExitThread(); } } } |
使用:
AppContextExt.GetInstance().Start(); AppContextExt.RegisterAssemblyServices(AppDomain.CurrentDomain.BaseDirectory + "ModuleService.dll");
ILogService svr = AppContextExt.Resolve<ILogService>(); if (svr != null) svr.LogInfo("OK");
解决方案截图:
作者:数据酷软件
出处:https://www.cnblogs.com/datacool/p/datacool_AppContext_IOC.html
关于作者:20年编程从业经验,持续关注MES/ERP/POS/WMS/工业自动化
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明。
联系方式: qq:71008973;wx:6857740733
基于人脸识别的考勤系统 地址: https://gitee.com/afeng124/viewface_attendance_ext
自己开发安卓应用框架 地址: https://gitee.com/afeng124/android-app-frame
WPOS(warehouse+pos) 后台演示地址: http://47.239.106.75:8080/
【推荐】国内首个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语句:使用策略模式优化代码结构