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

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 @ 2022-02-09 23:41  含泪拒绝王阿姨i  阅读(137)  评论(0)    收藏  举报