Custom IOC

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

 

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