ASP.NET Core中IOC容器的實(shí)現(xiàn)原理

本章將和大家分享ASP.NET Core中IOC容器的實(shí)現(xiàn)原理。
首先我們需要了解什么是IOC,為什么要使用IOC容器?
一、依賴
類A用到了類B,我們就說(shuō)類A依賴類B。

using System;
namespace MyIOCDI
{
public class Test
{
public void Show()
{
MyDependency myDependency = new MyDependency(); //全是細(xì)節(jié)
myDependency.Show();
Console.WriteLine($"This is {this.GetType().FullName}");
}
}
public class MyDependency
{
public void Show()
{
Console.WriteLine($"This is {this.GetType().FullName}");
}
}
}

上面的示例中,類Test就依賴了MyDependency類。
二、依賴倒置原則(Dependence Inversion Principle)
依賴倒置原則:高層模塊不應(yīng)該依賴于低層模塊,二者都應(yīng)該依賴于抽象。應(yīng)該依賴于抽象,而不是依賴細(xì)節(jié)。
什么是高層模塊?這里的使用者Test類就稱為高層模塊。什么是低層模塊?被使用者M(jìn)yDependency類就稱為低層模塊。上面的示例中我們的高層模塊就依賴于我們的低層模塊。
那么這樣子有什么不好呢?
1、面向?qū)ο笳Z(yǔ)言開(kāi)發(fā),就是類與類之間進(jìn)行交互,如果高層直接依賴低層的細(xì)節(jié),細(xì)節(jié)是多變的,那么低層的變化就導(dǎo)致上層的變化;
2、如果層數(shù)多了,低層的修改會(huì)直接水波效應(yīng)傳遞到最上層,一點(diǎn)細(xì)微的改動(dòng)都會(huì)導(dǎo)致整個(gè)系統(tǒng)從下往上的修改。
因此,上例按照依賴倒置原則修改如下:

using System;
namespace MyIOCDI
{
public class Test
{
public void Show()
{
IDepenency myDependency = new MyDependency(); //左邊抽象右邊細(xì)節(jié)
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();
}
}

三、IOC控制反轉(zhuǎn)
控制反轉(zhuǎn)是一種思想,所謂“控制反轉(zhuǎn)”就是反轉(zhuǎn)獲得依賴對(duì)象的過(guò)程。
上面示例經(jīng)過(guò)改造后雖然遵循了“依賴倒置原則”,但是違背了“開(kāi)放封閉原則”,因?yàn)槿绻幸惶煜胍薷淖兞縨yDependency為YourDependency類的實(shí)例,則需要修改Test類。
因此,我們需要反轉(zhuǎn)這種創(chuàng)建對(duì)象的過(guò)程:

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 的創(chuàng)建過(guò)程“反轉(zhuǎn)”給了調(diào)用者。
四、依賴注入(Dependency Injection)
依賴注入是一種在類及其依賴對(duì)象之間實(shí)現(xiàn)控制反轉(zhuǎn)(IOC)思想的技術(shù)。
所謂依賴注入,就是由IOC容器在運(yùn)行期間,動(dòng)態(tài)地將某種依賴關(guān)系注入到對(duì)象之中。
依賴注入就是能做到構(gòu)造某個(gè)對(duì)象時(shí),將依賴的對(duì)象自動(dòng)初始化并注入 。
IOC是目標(biāo)是效果,需要DI依賴注入的手段。
三種注入方式:構(gòu)造函數(shù)注入--屬性注入--方法注入(按時(shí)間順序)。
構(gòu)造函數(shù)注入用的最多,默認(rèn)找參數(shù)最多的構(gòu)造函數(shù),可以不用特性,可以去掉對(duì)容器的依賴。
五、IOC容器的實(shí)現(xiàn)原理
IOC容器的實(shí)現(xiàn)原理:
1、啟動(dòng)時(shí)保存注冊(cè)信息。
2、在構(gòu)造某個(gè)對(duì)象時(shí),根據(jù)注冊(cè)信息使用反射加特性,將依賴的對(duì)象自動(dòng)初始化并注入。
3、對(duì)對(duì)象進(jìn)行生命周期管理或者進(jìn)行AOP擴(kuò)展等。
下面我們重點(diǎn)來(lái)看下如何創(chuàng)建一個(gè)簡(jiǎn)易的IOC容器(當(dāng)然,實(shí)際使用的IOC容器要比這復(fù)雜的多)。
首先來(lái)看下項(xiàng)目的目錄結(jié)構(gòu):

此處IOC容器中用到的自定義特性如下所示:

using System;
namespace TianYaSharpCore.IOCDI.CustomAttribute
{
///
/// 構(gòu)造函數(shù)注入特性
///
[AttributeUsage(AttributeTargets.Constructor)]
public class ConstructorInjectionAttribute : Attribute
{
}
}


using System;
namespace TianYaSharpCore.IOCDI.CustomAttribute
{
///
/// 方法注入特性
///
[AttributeUsage(AttributeTargets.Method)]
public class MethodInjectionAttribute : Attribute
{
}
}


using System;
namespace TianYaSharpCore.IOCDI.CustomAttribute
{
///
/// 常量
///
[AttributeUsage(AttributeTargets.Parameter)]
public class ParameterConstantAttribute : Attribute
{
}
}


using System;
namespace TianYaSharpCore.IOCDI.CustomAttribute
{
///
/// 簡(jiǎn)稱(別名)
///
[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
{
///
/// 屬性注入特性
///
[AttributeUsage(AttributeTargets.Property)]
public class PropertyInjectionAttribute : Attribute
{
}
}

創(chuàng)建一個(gè)簡(jiǎn)易的IOC容器,如下所示:

using System;
namespace TianYaSharpCore.IOCDI.CustomContainer
{
public class IOCContainerRegistModel
{
public Type TargetType { get; set; }
///
/// 生命周期
///
public LifetimeType Lifetime { get; set; }
///
/// 僅限單例
///
public object SingletonInstance { get; set; }
}
///
/// 生命周期
///
public enum LifetimeType
{
Transient, //瞬時(shí)
Singleton,
Scope, //作用域
PerThread //線程單例
//外部可釋放單例
}
}


using System;
namespace TianYaSharpCore.IOCDI.CustomContainer
{
///
/// IOC容器接口
///
public interface ITianYaIOCContainer
{
void Register(string shortName = null, object[] paraList = null, LifetimeType lifetimeType = LifetimeType.Transient)
where TTo : TFrom;
TFrom Resolve(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
{
///
/// IOC容器
///
public class TianYaIOCContainer : ITianYaIOCContainer
{
#region 字段或者屬性
///
/// 保存注冊(cè)信息
///
private Dictionary<string, IOCContainerRegistModel> _tianYaContainerDictionary = new Dictionary<string, IOCContainerRegistModel>();
///
/// 保存常量的值
///
private Dictionary<string, object[]> _tianYaContainerValueDictionary = new Dictionary<string, object[]>();
///
/// 作用域單例的對(duì)象
///
private Dictionary<string, object> _tianYaContainerScopeDictionary = new Dictionary<string, object>();
#endregion 字段或者屬性
#region 構(gòu)造函數(shù)
///
/// 無(wú)參構(gòu)造行數(shù)
///
public TianYaIOCContainer()
{
}
///
/// 主要在創(chuàng)建子容器的時(shí)候使用
///
private TianYaIOCContainer(Dictionary<string, IOCContainerRegistModel> tianYaContainerDictionary,
Dictionary<string, object[]> tianYaContainerValueDictionary, Dictionary<string, object> tianYaContainerScopeDictionary)
{
this._tianYaContainerDictionary = tianYaContainerDictionary;
this._tianYaContainerValueDictionary = tianYaContainerValueDictionary;
this._tianYaContainerScopeDictionary = tianYaContainerScopeDictionary;
}
#endregion 構(gòu)造函數(shù)
///
/// 創(chuàng)建子容器
///
public ITianYaIOCContainer CreateChildContainer()
{
return new TianYaIOCContainer(this._tianYaContainerDictionary, this._tianYaContainerValueDictionary,
new Dictionary<string, object>()); //沒(méi)有注冊(cè)關(guān)系,最好能初始化進(jìn)去
}
///
/// 獲取鍵
///
private string GetKey(string fullName, string shortName) => $"{fullName}___{shortName}";
///
/// 加個(gè)參數(shù)區(qū)分生命周期--而且注冊(cè)關(guān)系得保存生命周期
///
///要添加的服務(wù)的類型
///要使用的實(shí)現(xiàn)的類型
/// 簡(jiǎn)稱(別名)(主要用于解決單接口多實(shí)現(xiàn))
/// 常量參數(shù)
/// 生命周期
public void Register(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);
}
}
///
/// 獲取對(duì)象
///
public TFrom Resolve(string shortName = null)
{
return (TFrom)this.ResolveObject(typeof(TFrom), shortName);
}
///
/// 遞歸--可以完成不限層級(jí)的對(duì)象創(chuàng)建
///
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 選擇合適的構(gòu)造函數(shù)
ConstructorInfo ctor = null;
//標(biāo)記特性
ctor = type.GetConstructors().FirstOrDefault(c => c.IsDefined(typeof(ConstructorInjectionAttribute), true));
if (ctor == null)
{
//參數(shù)個(gè)數(shù)最多
ctor = type.GetConstructors().OrderByDescending(c => c.GetParameters().Length).First();
}
//ctor = type.GetConstructors()[0]; //直接第一個(gè)
#endregion 選擇合適的構(gòu)造函數(shù)
#region 準(zhǔn)備構(gòu)造函數(shù)的參數(shù)
List<object> paraList = new List<object>();
object[] paraConstant = this._tianYaContainerValueDictionary.ContainsKey(key) ? this._tianYaContainerValueDictionary[key] : null; //常量找出來(lái)
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; //獲取參數(shù)的類型
string paraShortName = this.GetShortName(para);
object paraInstance = this.ResolveObject(paraType, paraShortName);
paraList.Add(paraInstance);
}
}
#endregion 準(zhǔn)備構(gòu)造函數(shù)的參數(shù)
object oInstance = null;
oInstance = Activator.CreateInstance(type, paraList.ToArray()); //創(chuàng)建對(duì)象,完成構(gòu)造函數(shù)的注入
#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;//獲取參數(shù)的類型 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擴(kuò)展
return oInstance;
}
///
/// 獲取簡(jiǎn)稱(別名)
///
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;
}
}
}
}

至此,我們就創(chuàng)建完了一個(gè)簡(jiǎn)易的IOC容器。
下面我們來(lái)添加一些用于測(cè)試的接口,如下所示:

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();
}
}

接口對(duì)應(yīng)的實(shí)現(xiàn),如下所示:

using System;
using MyIOCDI.IService;
namespace MyIOCDI.Service
{
public class TestServiceA : ITestServiceA
{
public TestServiceA()
{
Console.WriteLine($"{this.GetType().Name}被構(gòu)造。。。");
}
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}被構(gòu)造。。。");
}
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}被構(gòu)造。。。");
}
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
{
///
/// 屬性注入
///
[PropertyInjection]
public ITestServiceA TestServiceA { get; set; }
///
/// 帶有別名的屬性注入
///
[ParameterShortName("ServiceB")]
[PropertyInjection]
public ITestServiceB TestServiceB { get; set; }
public TestServiceD()
{
Console.WriteLine($"{this.GetType().Name}被構(gòu)造。。。");
}
#region 構(gòu)造函數(shù)注入
private readonly ITestServiceA _testServiceA;
private readonly ITestServiceB _testServiceB;
[ConstructorInjection] //優(yōu)先選擇帶有構(gòu)造函數(shù)注入特性的
public TestServiceD(ITestServiceA testServiceA, [ParameterConstant] string sValue, ITestServiceB testServiceB, [ParameterConstant] int iValue)
{
Console.WriteLine($"{this.GetType().Name}--{sValue}--{iValue}被構(gòu)造。。。");
_testServiceA = testServiceA;
_testServiceB = testServiceB;
}
#endregion 構(gòu)造函數(shù)注入
#region 方法注入
private ITestServiceC _testServiceC;
[MethodInjection]
public void Init(ITestServiceC testServiceC)
{
_testServiceC = testServiceC;
}
#endregion 方法注入
public void Show()
{
Console.WriteLine($"This is {this.GetType().Name} Show");
}
}
}

最后來(lái)看下IOC容器的使用及其運(yùn)行結(jié)果:

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();
{
//注冊(cè)
container.Register(); //將ITestServiceA注冊(cè)到TestServiceA
container.Register();
container.Register(shortName: "ServiceB");
container.Register();
container.Register(paraList: new object[] { "浪子天涯", 666 }, lifetimeType: LifetimeType.Singleton);
ITestServiceD d1 = container.Resolve(); //創(chuàng)建對(duì)象交給IOC容器
ITestServiceD d2 = container.Resolve();
d1.Show();
Console.WriteLine($"object.ReferenceEquals(d1, d2) = {object.ReferenceEquals(d1, d2)}");
}
Console.ReadKey();
}
}
}

運(yùn)行結(jié)果如下:

生命周期為作用域的,其實(shí)就是子容器單例,如下所示:

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();
//{
// //注冊(cè)
// container.Register(); //將ITestServiceA注冊(cè)到TestServiceA
// container.Register(); // container.Register(shortName: "ServiceB"); // container.Register(); // container.Register(paraList: new object[] { "浪子天涯", 666 }, lifetimeType: LifetimeType.Singleton); // ITestServiceD d1 = container.Resolve(); //創(chuàng)建對(duì)象交給IOC容器
// ITestServiceD d2 = container.Resolve(); // d1.Show();
// Console.WriteLine($"object.ReferenceEquals(d1, d2) = {object.ReferenceEquals(d1, d2)}");
//}
{
//生命周期:作用域
//就是Http請(qǐng)求時(shí),一個(gè)請(qǐng)求處理過(guò)程中,創(chuàng)建都是同一個(gè)實(shí)例;不同的請(qǐng)求處理過(guò)程中,就是不同的實(shí)例;
//得區(qū)分請(qǐng)求,Http請(qǐng)求---Asp.NetCore內(nèi)置Kestrel,初始化一個(gè)容器實(shí)例;然后每次來(lái)一個(gè)Http請(qǐng)求,就clone一個(gè),
//或者叫創(chuàng)建子容器(包含注冊(cè)關(guān)系),然后一個(gè)請(qǐng)求就一個(gè)子容器實(shí)例,那么就可以做到請(qǐng)求單例了(其實(shí)就是子容器單例)
//主要可以去做DbContext Repository
container.Register(lifetimeType: LifetimeType.Scope);
ITestServiceA a1 = container.Resolve();
ITestServiceA a2 = container.Resolve();
Console.WriteLine(object.ReferenceEquals(a1, a2)); //T
ITianYaIOCContainer container1 = container.CreateChildContainer();
ITestServiceA a11 = container1.Resolve();
ITestServiceA a12 = container1.Resolve();
ITianYaIOCContainer container2 = container.CreateChildContainer();
ITestServiceA a21 = container2.Resolve();
ITestServiceA a22 = container2.Resolve();
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();
}
}
}

運(yùn)行結(jié)果如下:

至此本文就全部介紹完了,如果覺(jué)得對(duì)您有所啟發(fā)請(qǐng)記得點(diǎn)個(gè)贊哦?。?!
?
Demo源碼:
鏈接:https://pan.baidu.com/s/15xpmWbEDbkm7evpr4iIZNg
提取碼:ckes
往期精彩回顧
【推薦】.NET Core開(kāi)發(fā)實(shí)戰(zhàn)視頻課程?★★★
Redis基本使用及百億數(shù)據(jù)量中的使用技巧分享(附視頻地址及觀看指南)
.NET Core中的一個(gè)接口多種實(shí)現(xiàn)的依賴注入與動(dòng)態(tài)選擇看這篇就夠了
10個(gè)小技巧助您寫出高性能的ASP.NET Core代碼
現(xiàn)身說(shuō)法:實(shí)際業(yè)務(wù)出發(fā)分析百億數(shù)據(jù)量下的多表查詢優(yōu)化
關(guān)于C#異步編程你應(yīng)該了解的幾點(diǎn)建議
