本章將和你們分享ASP.NET Core中IOC容器的實現原理。html
首先咱們須要瞭解什麼是IOC,爲何要使用IOC容器?ide
類A用到了類B,咱們就說類A依賴類B。函數
using System; namespace MyIOCDI { public class Test { public void Show() { MyDependency myDependency = new MyDependency(); //全是細節 myDependency.Show(); Console.WriteLine($"This is {this.GetType().FullName}"); } } public class MyDependency { public void Show() { Console.WriteLine($"This is {this.GetType().FullName}"); } } }
上面的示例中,類Test就依賴了MyDependency類。測試
依賴倒置原則:高層模塊不該該依賴於低層模塊,兩者都應該依賴於抽象。應該依賴於抽象,而不是依賴細節。this
什麼是高層模塊?這裏的使用者Test類就稱爲高層模塊。什麼是低層模塊?被使用者MyDependency類就稱爲低層模塊。上面的示例中咱們的高層模塊就依賴於咱們的低層模塊。spa
那麼這樣子有什麼很差呢?線程
一、面嚮對象語言開發,就是類與類之間進行交互,若是高層直接依賴低層的細節,細節是多變的,那麼低層的變化就致使上層的變化;3d
二、若是層數多了,低層的修改會直接水波效應傳遞到最上層,一點細微的改動都會致使整個系統從下往上的修改。code
所以,上例按照依賴倒置原則修改以下:htm
using System; namespace MyIOCDI { public class Test { public void Show() { IDepenency myDependency = new MyDependency(); //左邊抽象右邊細節 myDependency.Show(); Console.WriteLine($"This is {this.GetType().FullName}"); } } public class MyDependency : IDepenency { public void Show() { Console.WriteLine($"This is {this.GetType().FullName}"); } } public interface IDepenency { void Show(); } }
控制反轉是一種思想,所謂「控制反轉」就是反轉得到依賴對象的過程。
上面示例通過改造後雖然遵循了「依賴倒置原則」,可是違背了「開放封閉原則」,由於若是有一天想要修改變量myDependency爲YourDependency類的實例,則須要修改Test類。
所以,咱們須要反轉這種建立對象的過程:
using System; namespace MyIOCDI { public class Test { private readonly IDepenency _myDependency; public Test(IDepenency myDependency) { this._myDependency = myDependency; } public void Show() { _myDependency.Show(); Console.WriteLine($"This is {this.GetType().FullName}"); } } public class MyDependency : IDepenency { public void Show() { Console.WriteLine($"This is {this.GetType().FullName}"); } } public interface IDepenency { void Show(); } }
上例中,將 _myDependency 的建立過程「反轉」給了調用者。
依賴注入是一種在類及其依賴對象之間實現控制反轉(IOC)思想的技術。
所謂依賴注入,就是由IOC容器在運行期間,動態地將某種依賴關係注入到對象之中。
依賴注入就是能作到構造某個對象時,將依賴的對象自動初始化並注入 。
IOC是目標是效果,須要DI依賴注入的手段。
三種注入方式:構造函數注入--屬性注入--方法注入(按時間順序)。
構造函數注入用的最多,默認找參數最多的構造函數,能夠不用特性,能夠去掉對容器的依賴。
IOC容器的實現原理:
一、啓動時保存註冊信息。
二、在構造某個對象時,根據註冊信息使用反射加特性,將依賴的對象自動初始化並注入。
三、對對象進行生命週期管理或者進行AOP擴展等。
下面咱們重點來看下如何建立一個簡易的IOC容器(固然,實際使用的IOC容器要比這複雜的多)。
首先來看下項目的目錄結構:
此處IOC容器中用到的自定義特性以下所示:
using System; namespace TianYaSharpCore.IOCDI.CustomAttribute { /// <summary> /// 構造函數注入特性 /// </summary> [AttributeUsage(AttributeTargets.Constructor)] public class ConstructorInjectionAttribute : Attribute { } }
using System; namespace TianYaSharpCore.IOCDI.CustomAttribute { /// <summary> /// 方法注入特性 /// </summary> [AttributeUsage(AttributeTargets.Method)] public class MethodInjectionAttribute : Attribute { } }
using System; namespace TianYaSharpCore.IOCDI.CustomAttribute { /// <summary> /// 常量 /// </summary> [AttributeUsage(AttributeTargets.Parameter)] public class ParameterConstantAttribute : Attribute { } }
using System; namespace TianYaSharpCore.IOCDI.CustomAttribute { /// <summary> /// 簡稱(別名) /// </summary> [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] public class ParameterShortNameAttribute : Attribute { public string ShortName { get; private set; } public ParameterShortNameAttribute(string shortName) { this.ShortName = shortName; } } }
using System; namespace TianYaSharpCore.IOCDI.CustomAttribute { /// <summary> /// 屬性注入特性 /// </summary> [AttributeUsage(AttributeTargets.Property)] public class PropertyInjectionAttribute : Attribute { } }
建立一個簡易的IOC容器,以下所示:
using System; namespace TianYaSharpCore.IOCDI.CustomContainer { public class IOCContainerRegistModel { public Type TargetType { get; set; } /// <summary> /// 生命週期 /// </summary> public LifetimeType Lifetime { get; set; } /// <summary> /// 僅限單例 /// </summary> public object SingletonInstance { get; set; } } /// <summary> /// 生命週期 /// </summary> public enum LifetimeType { Transient, //瞬時 Singleton, Scope, //做用域 PerThread //線程單例 //外部可釋放單例 } }
using System; namespace TianYaSharpCore.IOCDI.CustomContainer { /// <summary> /// IOC容器接口 /// </summary> public interface ITianYaIOCContainer { void Register<TFrom, TTo>(string shortName = null, object[] paraList = null, LifetimeType lifetimeType = LifetimeType.Transient) where TTo : TFrom; TFrom Resolve<TFrom>(string shortName = null); ITianYaIOCContainer CreateChildContainer(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using TianYaSharpCore.IOCDI.CustomAttribute; namespace TianYaSharpCore.IOCDI.CustomContainer { /// <summary> /// IOC容器 /// </summary> public class TianYaIOCContainer : ITianYaIOCContainer { #region 字段或者屬性 /// <summary> /// 保存註冊信息 /// </summary> private Dictionary<string, IOCContainerRegistModel> _tianYaContainerDictionary = new Dictionary<string, IOCContainerRegistModel>(); /// <summary> /// 保存常量的值 /// </summary> private Dictionary<string, object[]> _tianYaContainerValueDictionary = new Dictionary<string, object[]>(); /// <summary> /// 做用域單例的對象 /// </summary> private Dictionary<string, object> _tianYaContainerScopeDictionary = new Dictionary<string, object>(); #endregion 字段或者屬性 #region 構造函數 /// <summary> /// 無參構造行數 /// </summary> public TianYaIOCContainer() { } /// <summary> /// 主要在建立子容器的時候使用 /// </summary> private TianYaIOCContainer(Dictionary<string, IOCContainerRegistModel> tianYaContainerDictionary, Dictionary<string, object[]> tianYaContainerValueDictionary, Dictionary<string, object> tianYaContainerScopeDictionary) { this._tianYaContainerDictionary = tianYaContainerDictionary; this._tianYaContainerValueDictionary = tianYaContainerValueDictionary; this._tianYaContainerScopeDictionary = tianYaContainerScopeDictionary; } #endregion 構造函數 /// <summary> /// 建立子容器 /// </summary> public ITianYaIOCContainer CreateChildContainer() { return new TianYaIOCContainer(this._tianYaContainerDictionary, this._tianYaContainerValueDictionary, new Dictionary<string, object>()); //沒有註冊關係,最好能初始化進去 } /// <summary> /// 獲取鍵 /// </summary> private string GetKey(string fullName, string shortName) => $"{fullName}___{shortName}"; /// <summary> /// 加個參數區分生命週期--並且註冊關係得保存生命週期 /// </summary> /// <typeparam name="TFrom">要添加的服務的類型</typeparam> /// <typeparam name="TTo">要使用的實現的類型</typeparam> /// <param name="shortName">簡稱(別名)(主要用於解決單接口多實現)</param> /// <param name="paraList">常量參數</param> /// <param name="lifetimeType">生命週期</param> public void Register<TFrom, TTo>(string shortName = null, object[] paraList = null, LifetimeType lifetimeType = LifetimeType.Transient) where TTo : TFrom { this._tianYaContainerDictionary.Add(this.GetKey(typeof(TFrom).FullName, shortName), new IOCContainerRegistModel() { Lifetime = lifetimeType, TargetType = typeof(TTo) }); if (paraList != null && paraList.Length > 0) { this._tianYaContainerValueDictionary.Add(this.GetKey(typeof(TFrom).FullName, shortName), paraList); } } /// <summary> /// 獲取對象 /// </summary> public TFrom Resolve<TFrom>(string shortName = null) { return (TFrom)this.ResolveObject(typeof(TFrom), shortName); } /// <summary> /// 遞歸--能夠完成不限層級的對象建立 /// </summary> private object ResolveObject(Type abstractType, string shortName = null) { string key = this.GetKey(abstractType.FullName, shortName); var model = this._tianYaContainerDictionary[key]; #region 生命週期 switch (model.Lifetime) { case LifetimeType.Transient: Console.WriteLine("Transient Do Nothing Before"); break; case LifetimeType.Singleton: if (model.SingletonInstance == null) { break; } else { return model.SingletonInstance; } case LifetimeType.Scope: if (this._tianYaContainerScopeDictionary.ContainsKey(key)) { return this._tianYaContainerScopeDictionary[key]; } else { break; } default: break; } #endregion 生命週期 Type type = model.TargetType; #region 選擇合適的構造函數 ConstructorInfo ctor = null; //標記特性 ctor = type.GetConstructors().FirstOrDefault(c => c.IsDefined(typeof(ConstructorInjectionAttribute), true)); if (ctor == null) { //參數個數最多 ctor = type.GetConstructors().OrderByDescending(c => c.GetParameters().Length).First(); } //ctor = type.GetConstructors()[0]; //直接第一個 #endregion 選擇合適的構造函數 #region 準備構造函數的參數 List<object> paraList = new List<object>(); object[] paraConstant = this._tianYaContainerValueDictionary.ContainsKey(key) ? this._tianYaContainerValueDictionary[key] : null; //常量找出來 int iIndex = 0; foreach (var para in ctor.GetParameters()) { if (para.IsDefined(typeof(ParameterConstantAttribute), true)) { paraList.Add(paraConstant[iIndex]); iIndex++; } else { Type paraType = para.ParameterType; //獲取參數的類型 string paraShortName = this.GetShortName(para); object paraInstance = this.ResolveObject(paraType, paraShortName); paraList.Add(paraInstance); } } #endregion 準備構造函數的參數 object oInstance = null; oInstance = Activator.CreateInstance(type, paraList.ToArray()); //建立對象,完成構造函數的注入 #region 屬性注入 foreach (var prop in type.GetProperties().Where(p => p.IsDefined(typeof(PropertyInjectionAttribute), true))) { Type propType = prop.PropertyType; string paraShortName = this.GetShortName(prop); object propInstance = this.ResolveObject(propType, paraShortName); prop.SetValue(oInstance, propInstance); } #endregion 屬性注入 #region 方法注入 foreach (var method in type.GetMethods().Where(m => m.IsDefined(typeof(MethodInjectionAttribute), true))) { List<object> paraInjectionList = new List<object>(); foreach (var para in method.GetParameters()) { Type paraType = para.ParameterType;//獲取參數的類型 IUserDAL string paraShortName = this.GetShortName(para); object paraInstance = this.ResolveObject(paraType, paraShortName); paraInjectionList.Add(paraInstance); } method.Invoke(oInstance, paraInjectionList.ToArray()); } #endregion 方法注入 #region 生命週期 switch (model.Lifetime) { case LifetimeType.Transient: Console.WriteLine("Transient Do Nothing After"); break; case LifetimeType.Singleton: model.SingletonInstance = oInstance; break; case LifetimeType.Scope: this._tianYaContainerScopeDictionary[key] = oInstance; break; default: break; } #endregion 生命週期 //return oInstance.AOP(abstractType); //AOP擴展 return oInstance; } /// <summary> /// 獲取簡稱(別名) /// </summary> private string GetShortName(ICustomAttributeProvider provider) { if (provider.IsDefined(typeof(ParameterShortNameAttribute), true)) { var attribute = (ParameterShortNameAttribute)(provider.GetCustomAttributes(typeof(ParameterShortNameAttribute), true)[0]); return attribute.ShortName; } else { return null; } } } }
至此,咱們就建立完了一個簡易的IOC容器。
下面咱們來添加一些用於測試的接口,以下所示:
using System; namespace MyIOCDI.IService { public interface ITestServiceA { void Show(); } }
using System; namespace MyIOCDI.IService { public interface ITestServiceB { void Show(); } }
using System; namespace MyIOCDI.IService { public interface ITestServiceC { void Show(); } }
using System; namespace MyIOCDI.IService { public interface ITestServiceD { void Show(); } }
接口對應的實現,以下所示:
using System; using MyIOCDI.IService; namespace MyIOCDI.Service { public class TestServiceA : ITestServiceA { public TestServiceA() { Console.WriteLine($"{this.GetType().Name}被構造。。。"); } public void Show() { Console.WriteLine($"This is {this.GetType().Name} Show"); } } }
using System; using MyIOCDI.IService; namespace MyIOCDI.Service { public class TestServiceB : ITestServiceB { public TestServiceB() { Console.WriteLine($"{this.GetType().Name}被構造。。。"); } public void Show() { Console.WriteLine($"This is {this.GetType().Name} Show"); } } }
using System; using MyIOCDI.IService; namespace MyIOCDI.Service { public class TestServiceC : ITestServiceC { public TestServiceC() { Console.WriteLine($"{this.GetType().Name}被構造。。。"); } public void Show() { Console.WriteLine($"This is {this.GetType().Name} Show"); } } }
using System; using MyIOCDI.IService; using TianYaSharpCore.IOCDI.CustomAttribute; namespace MyIOCDI.Service { public class TestServiceD : ITestServiceD { /// <summary> /// 屬性注入 /// </summary> [PropertyInjection] public ITestServiceA TestServiceA { get; set; } /// <summary> /// 帶有別名的屬性注入 /// </summary> [ParameterShortName("ServiceB")] [PropertyInjection] public ITestServiceB TestServiceB { get; set; } public TestServiceD() { Console.WriteLine($"{this.GetType().Name}被構造。。。"); } #region 構造函數注入 private readonly ITestServiceA _testServiceA; private readonly ITestServiceB _testServiceB; [ConstructorInjection] //優先選擇帶有構造函數注入特性的 public TestServiceD(ITestServiceA testServiceA, [ParameterConstant] string sValue, ITestServiceB testServiceB, [ParameterConstant] int iValue) { Console.WriteLine($"{this.GetType().Name}--{sValue}--{iValue}被構造。。。"); _testServiceA = testServiceA; _testServiceB = testServiceB; } #endregion 構造函數注入 #region 方法注入 private ITestServiceC _testServiceC; [MethodInjection] public void Init(ITestServiceC testServiceC) { _testServiceC = testServiceC; } #endregion 方法注入 public void Show() { Console.WriteLine($"This is {this.GetType().Name} Show"); } } }
最後來看下IOC容器的使用及其運行結果:
using System; using TianYaSharpCore.IOCDI.CustomContainer; using MyIOCDI.IService; using MyIOCDI.Service; namespace MyIOCDI { class Program { static void Main(string[] args) { ITianYaIOCContainer container = new TianYaIOCContainer(); { //註冊 container.Register<ITestServiceA, TestServiceA>(); //將ITestServiceA註冊到TestServiceA container.Register<ITestServiceB, TestServiceB>(); container.Register<ITestServiceB, TestServiceB>(shortName: "ServiceB"); container.Register<ITestServiceC, TestServiceC>(); container.Register<ITestServiceD, TestServiceD>(paraList: new object[] { "浪子天涯", 666 }, lifetimeType: LifetimeType.Singleton); ITestServiceD d1 = container.Resolve<ITestServiceD>(); //建立對象交給IOC容器 ITestServiceD d2 = container.Resolve<ITestServiceD>(); d1.Show(); Console.WriteLine($"object.ReferenceEquals(d1, d2) = {object.ReferenceEquals(d1, d2)}"); } Console.ReadKey(); } } }
運行結果以下:
生命週期爲做用域的,其實就是子容器單例,以下所示:
using System; using TianYaSharpCore.IOCDI.CustomContainer; using MyIOCDI.IService; using MyIOCDI.Service; namespace MyIOCDI { class Program { static void Main(string[] args) { ITianYaIOCContainer container = new TianYaIOCContainer(); //{ // //註冊 // container.Register<ITestServiceA, TestServiceA>(); //將ITestServiceA註冊到TestServiceA // container.Register<ITestServiceB, TestServiceB>(); // container.Register<ITestServiceB, TestServiceB>(shortName: "ServiceB"); // container.Register<ITestServiceC, TestServiceC>(); // container.Register<ITestServiceD, TestServiceD>(paraList: new object[] { "浪子天涯", 666 }, lifetimeType: LifetimeType.Singleton); // ITestServiceD d1 = container.Resolve<ITestServiceD>(); //建立對象交給IOC容器 // ITestServiceD d2 = container.Resolve<ITestServiceD>(); // d1.Show(); // Console.WriteLine($"object.ReferenceEquals(d1, d2) = {object.ReferenceEquals(d1, d2)}"); //} { //生命週期:做用域 //就是Http請求時,一個請求處理過程當中,建立都是同一個實例;不一樣的請求處理過程當中,就是不一樣的實例; //得區分請求,Http請求---Asp.NetCore內置Kestrel,初始化一個容器實例;而後每次來一個Http請求,就clone一個, //或者叫建立子容器(包含註冊關係),而後一個請求就一個子容器實例,那麼就能夠作到請求單例了(其實就是子容器單例) //主要能夠去作DbContext Repository container.Register<ITestServiceA, TestServiceA>(lifetimeType: LifetimeType.Scope); ITestServiceA a1 = container.Resolve<ITestServiceA>(); ITestServiceA a2 = container.Resolve<ITestServiceA>(); Console.WriteLine(object.ReferenceEquals(a1, a2)); //T ITianYaIOCContainer container1 = container.CreateChildContainer(); ITestServiceA a11 = container1.Resolve<ITestServiceA>(); ITestServiceA a12 = container1.Resolve<ITestServiceA>(); ITianYaIOCContainer container2 = container.CreateChildContainer(); ITestServiceA a21 = container2.Resolve<ITestServiceA>(); ITestServiceA a22 = container2.Resolve<ITestServiceA>(); Console.WriteLine(object.ReferenceEquals(a11, a12)); //T Console.WriteLine(object.ReferenceEquals(a21, a22)); //T Console.WriteLine(object.ReferenceEquals(a11, a21)); //F Console.WriteLine(object.ReferenceEquals(a11, a22)); //F Console.WriteLine(object.ReferenceEquals(a12, a21)); //F Console.WriteLine(object.ReferenceEquals(a12, a22)); //F } Console.ReadKey(); } } }
運行結果以下:
至此本文就所有介紹完了,若是以爲對您有所啓發請記得點個贊哦!!!
Demo源碼:
連接:https://pan.baidu.com/s/15xpmWbEDbkm7evpr4iIZNg 提取碼:ckes
此文由博主精心撰寫轉載請保留此原文連接:https://www.cnblogs.com/xyh9039/p/13663808.html