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