諾禾、動手造輪子

代碼修正#
FromServiceAttribute#
完好的代碼修正可以參考這個 commit https://github.com/WeihanLi/WeihanLi.Common/commit/91dc0b515d12e7c036771fba9419824cd0219544

首先我們需求增加一個 FromServiceAttribute 用來標識哪些屬性需求注入,代碼如下:

Copy
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public sealed class FromServiceAttribute : Attribute
{
}
這裏 AttributeTargets 除了屬性之外增加了字段和參數,是想可能以後會用到,參數典型的應用場景就是類似於 asp.net core 裏的 [FromServices] 用來完成方法注入參數

EnrichObject#
增加了一個 EnrichObject 方法,用來在獲取到效勞實例之後,對效勞實例做一些補充的配置,如我們要加的屬性注入,假設我們要加字段注入等也可以在這個方法內完成,來看完成:

Copy
private object EnrichObject(object obj)
{
if (null != obj)
{
// PropertyInjection
var type = obj.GetType();
foreach (var property in CacheUtil.TypePropertyCache.GetOrAdd(type, t => t.GetProperties())
.Where(x => x.IsDefined(typeof(FromServiceAttribute))))
{
if (property.GetValueGetter()?.Invoke(obj) == null)
{
property.GetValueSetter()?.Invoke(
obj,
GetService(property.PropertyType)
);
}
}
}

return obj;

}
上面的邏輯就是獲取這個 object 定義的一切需求注入的屬性,假設屬性的值不爲 null 則,從效勞容器中獲取對應的效勞實例,之所以要檢查是不是null

上面的 CacheUtil.TypePropertyCache 是一個 Type 爲 key,PropertyInfo 數組爲 Value 的併發字典,用來緩存類型的屬性

GetValueGetter/GetValueSetter 是 PropertyInfo 的擴展方法,應用表達式樹緩和存進步屬性 Get/Set 的效率

GetSertviceInstance#
修正原來的 GetServiceInstance 方法爲 GetServiceInstanceInternal,增加一個一樣的方法,完成邏輯是在 GetServiceInstanceInternal 的基礎上調用上面的 Enrich 方法來完成屬性注入

More#
固然增加了屬性注入的支持,但是還是不太舉薦運用,從上面屬性注入的代碼中可以看得到,假設用不好很容易呈現循環依賴的問題,而且用構造器注入的話依賴關係很明晰,分析方法的構造方法即可,假設要運用屬性注入請謹慎運用

Reference#
https://github.com/WeihanLi/WeihanLi.Common/commit/91dc0b515d12e7c036771fba9419824cd0219544
https://github.com/WeihanLi/WeihanLi.Common/tree/dev/src/WeihanLi.Common/DependencyInjection
https://www.cnblogs.com/weihanli/p/implement-dependency-injection.html
https://www.cnblogs.com/weihanli/p/implement-dependency-injection-01.html
https://www.cnblogs.com/weihanli/p/implement-dependency-injection-02.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章