.Net Core依赖注入原理简单实现

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
var app = new MyApplication();
 
app.Services.AddTransient<ITestServices, TestServices>();
 
app.Services.AddTransient<ITestServices2, TestServices2>();
 
var a = app.Services.GetService<ITestServices>();
 
var b = app.Services.GetService<ITestServices2>();
 
Console.WriteLine(a.GetData());
 
Console.WriteLine(b.GetData());
public class MyApplication
{
    public Dictionary<Type, Type> Services { get; set; } = new Dictionary<Type, Type>();
}
 
public static class MyApplicationExtensions
{
    public static Dictionary<Type, Type> AddTransient<IServices, Impliment>(this Dictionary<Type, Type> services) where IServices : class
    where Impliment : class, IServices
    {
        services.Add(typeof(IServices), typeof(Impliment));
        return services;
    }
    public static object GetService(this Dictionary<Type, Type> services, Type tServices)
    {
        var tImplement = services.ContainsKey(tServices) ? services[tServices] : null;
 
        object? value = null;
 
        if (tImplement != null)
        {
            var ctor = tImplement.GetConstructors().OrderByDescending(x => x.GetParameters().Count()).FirstOrDefault();
 
            var ctorParams = ctor.GetParameters();
 
            var ParamsList = new List<object>();
 
            //循环加递归依次拿到对应构造参数
 
            foreach (var ctorParam in ctorParams)
            {
                ParamsList.Add(services.GetService(ctorParam.ParameterType));
            }
 
            value = ctor.Invoke(ParamsList.ToArray());
        }
 
        return value;
    }
 
    public static IServices GetService<IServices>(this Dictionary<Type, Type> services)
    {
        return (IServices)services.GetService(typeof(IServices));
    }
}

 

posted @   含泪拒绝王阿姨i  阅读(128)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示