前言:在平時的寫代碼中爲了解耦、方便擴展,常用一些DI容器(如:Autofac、Unity),那是特別的好用。spa
關於它的底層實現代碼 大概是這樣。code
1、使用依賴注入的好處xml
關於使用依賴注入建立對象的好處網上一找就是一大堆(低耦合、可配置等),這裏就不復制粘貼了。對象
2、使用XML+Assembly實現可配置的Containerblog
namespace com.cqgc.TestSys.Core { public class Container { private static Container instance;//實例 private static XDocument xml;//UI層的服務實現配置文件實例 public static Container Instance//全局IOC窗口實例,單例模式 { get { if (instance == null) { instance = new Container(); } if (xml == null) { //讀取UI層的服務實現配置文件 xml = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "/Configuration/Service.xml"); } return instance; } } /// <summary> /// 向外提供建立對象的方法 /// </summary> /// <typeparam name="T">Service</typeparam> /// <returns></returns> public T Resolve<T>() where T : class { return GetComponentInstance<T>(typeof(T).Name); } /// <summary> /// 經過XMl中的Service名建立對應的業務邏輯實體 /// </summary> /// <typeparam name="T">Component</typeparam> /// <param name="service">Service名字</param> /// <returns>Component</returns> public T GetComponentInstance<T>(string service) where T : class { //沒找到配置文件 if (xml == null) { throw new ArgumentNullException("沒找到配置文件"+ nameof(xml)); } //在UI層的服務實現配置文件根據接口文件名讀取實現接口文件的業務邏輯實體 var element = (from p in xml.Root.Elements("element") where p.Attribute("Id").Value.Equals(service) select new { serviceNamespace = p.Attribute("Service").Value, classNamespace = p.Attribute("Class").Value }).FirstOrDefault(); //沒找到配置節點 if (string.IsNullOrEmpty(element.classNamespace)) { throw new Exception("配置文件結點" + service + "出錯!"); } string[] configs = element.classNamespace.Split(','); //XML配置中接口和業務邏輯實體不成對 if (configs.Length != 2) { throw new Exception("配置文件結點" + service + "出錯!"); } ProxyGenerator generator = new ProxyGenerator();//代碼生成器 T t = (T)Assembly.Load(configs[1]).CreateInstance(configs[0]);//根據配置文件實例化一個對象 return t; } //釋放資源 public void Dispose() { instance = null; xml = null; } } }
3、XML接口
<?xml version="1.0" encoding="utf-8" ?> <root> <element Id="IUserService" Service="com.cqgc.TestSys.Service.IUserService, com.cqgc.TestSys.Service" Class="com.cqgc.TestSys.Component.UserComponent, com.cqgc.TestSys.Component"></element> <element Id="ISysUserService" Service="com.cqgc.TestSys.Service.ISysUserService, com.cqgc.TestSys.Service" Class="com.cqgc.TestSys.Component.SysUserComponent, com.cqgc.TestSys.Component"></element> </root>
4、調用utf-8
var _user=Container.Instance.Resolve<ISysUserService>();