反射实例--自己写个简单的IOC容器

一、先来看看项目的简单结构

 

 

二、新增类库:DemoIOC.IRepository

1.在类库下新建接口:IDemoRepository.cs

public interface IDemoRepository
{
    void Query();
}

三、新增类库:DemoIOC.Repository

1.在类库下新建类:DemoRepository.cs,继承接口:IDemoRepository.cs,并且实现接口的方法

public class DemoRepository : IDemoRepository
{
        public void Query()
        {
            Console.WriteLine("DemoRepository 的Query方法");
        }
}

四、新增类库:DemoIOC.IService

1.在类库下新建接口:IDemoService.cs

public interface IDemoService
{
        void Query();
}

五、新增类库:DemoIOC.Service

1.在类库下新建类:DemoService.cs ,继续接口:IDemoService.cs,并实现接口方法

2.新增构造函数,并且传入参数:IDemoRepository,用于实现函数注入

public class DemoService : IDemoService
{
        private readonly IDemoRepository _demoRepository;
        public DemoService(IDemoRepository demoRepository)
        {
            _demoRepository = demoRepository;
        }

        public void Query()
        {
            _demoRepository.Query();
        }
}

六、新增控制台程序:DemoIOC

1.新增类:ContainerIOC.cs  用于实现依赖注入

public class ContainerIOC
{
        private readonly Dictionary<string, Type> dic = new Dictionary<string, Type>();

        public  void Register<TFrom, TTo>() where TTo : TFrom
        {
            var fromName = typeof(TFrom).FullName;
            dic.Add(fromName, typeof(TTo));
        }

        public TFrom Resolve<TFrom>()
        {
            Type fromType = typeof(TFrom);
            return (TFrom)ResolveObject<TFrom>(fromType);
        }

        private object ResolveObject<TFrom>(Type type)
        {
            var key = type.FullName;
            Type toType = dic[key];
            var ctors = toType.GetConstructors();
            List<object> parameterList = new List<object>();
            foreach (var ctor in ctors)
            {
                var parameters = ctor.GetParameters();
                foreach (var parameter in parameters)
                {
                    var parameterType = parameter.ParameterType;
                    var parameterInstance = ResolveObject<TFrom>(parameterType);
                    parameterList.Add(parameterInstance);
                }
            }
            return Activator.CreateInstance(toType, parameterList.ToArray());
        }
}

七、测试结果

class Program
{
        static void Main(string[] args)
        {
            ContainerIOC container = new ContainerIOC();
            container.Register<IDemoRepository, DemoRepository>();
            container.Register<IDemoService, DemoService>();
            IDemoService repository = container.Resolve<IDemoService>();
            repository.Query();
        }
}

 

 

 

posted @ 2020-09-05 11:33  字里行间  阅读(164)  评论(0编辑  收藏  举报