using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WebApplication2
{
public class CustomContainer:ICustomContainer
{
private Dictionary<string, Type> cache = new Dictionary<string, Type>();
public void Register<TInterface, TImp>() where TImp : TInterface
{
cache.Add(typeof(TInterface).FullName, typeof(TImp));
}
public TInterface Resolve<TInterface>(string name)
{
return (TInterface)resolveObj(name);
}
//若類裏面有類,有如何處理
private object resolveObj(string name)
{
if (!cache.ContainsKey(name))
{
throw new Exception("the class is not registered");
}
var value = cache[name];
// muliple construct, to use the one, which has the most parameters.
var construct = value.GetConstructors().OrderByDescending(g => g.GetParameters().Length).First();
List<object> paras = new List<object>();
foreach (var par in construct.GetParameters())
{
paras.Add(resolveObj(par.ParameterType.FullName));
}
//if (paras.Count() == 0)
//{
// return Activator.CreateInstance(value);
//}
return Activator.CreateInstance(value
, paras.ToArray());
}
}
}