当前位置: 移动技术网 > IT编程>开发语言>.net > 手写实现简单版IOC

手写实现简单版IOC

2019年03月21日  | 移动技术网IT编程  | 我要评论

喜爱夜蒲2高清,康熙来了20130304,美女qq群

概述

ioc (inversion of control) 控制反转,大家应该都比较熟悉了、应该也都有用过,这里就不具体介绍了。自己平时也有用到过ioc,但是对它的具体实现原理只有一个模糊的概念,所以决定自己手动实现一个简单ioc。

开始

首先呢我们得知道ioc的主要作用是什么,才能开始动手写。ioc主要不就是负责创建对象以及管理生命周期嘛,那我们就开始动手啦。

比如现在有一个ianimal接口animal继承接口,然后就是个call的方法。一般我们使用的时候都是ianimal animal=new animal(); 如果是使用第三方ioc容器实现的话,我们需要先注册一下类型才能获取到实例。

所以我们先来个最简单的仿照这个过程:

新建一个container,然后里面有一个类型注册的方法resgistertype和一个返回实例的方法rerolve,还有一个存储类型的字典,具体代码如下

        private static dictionary<string, object> containertypedictionary = new dictionary<string, object>();/// <summary>
        /// 注册类型
        /// </summary>
        /// <typeparam name="it"></typeparam>
        /// <typeparam name="t"></typeparam>
        public void resgistertype<it,t>()
        {
            if (!containertypedictionary.containskey(typeof(it).fullname))
                containertypedictionary.add(typeof(it).fullname, typeof(t));
        }

        /// <summary>
        /// 根据注册信息生成实例
        /// </summary>
        /// <typeparam name="it"></typeparam>
        /// <returns></returns>
        public it rerolve<it>()
        {
            string key = typeof(it).fullname;
            type type = (type)containertypedictionary[key];
       return (it)activator.createinstance(type);
     }

然后我们新建一个控制台测试一下

container container = new container();
container.resgistertype<ianimal, animal>();
ianimal animal= container.rerolve<ianimal>();

然后可以在不依赖具体对象animal的情况下成功的创建一个animal实例。

 

之后我们就可以考虑复杂一点的情况了,现在我们的animal类里没有做任何事,假如它的构造函数里依赖于另一个对象呢,这样我们的程序肯定是会报错的。比如下面这样:

public class animal: ianimal
    {
        public animal(dog dog)
        {
            
        }
    }

 

我们容器目前能创建的对象实例,只有通过resgistertype方法注册过类型的,而像animal里依赖的不能实现创建,所以这个时候就需要用到依赖注入了。

关于依赖注入与控制反转的关系,我个人的理解是:控制反转是一种设计思想,而依赖注入则是实现控制反转思想的方法。

ioc容器一般依赖注入有三种:构造函数注入、方法注入、属性注入。

那么我们就来照瓢画葫芦,实现一下构造函数注入。一般ioc容器构造函数注入是通过一个特性来识别注入的,如果没有标记特性则去找构造函数参数个数最多的,我们就按照这个思路来。

首先我们新建一个linjectionconstructorattribute类,只需继承attribute就行了。

 

public class linjectionconstructorattribute :attribute
    {
    }

 

然后在刚才那个animal构造函数上标记上特性,接下来就开始写代码。

/// <summary>
        /// 根据注册信息生成实例
        /// </summary>
        /// <typeparam name="it"></typeparam>
        /// <returns></returns>
        public it rerolve<it>()
        {
            string key = typeof(it).fullname;
            type type = (type)containertypedictionary[key];

            return (it)createtype(type);
        }
/// <summary>
        /// 根据提供的类型创建类型实例并返回
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private object createtype(type type)
        {
            var ctorarray = type.getconstructors();
            if (ctorarray.count(c => c.isdefined(typeof(linjectionconstructorattribute), true)) > 0)
            {
                //获取带特性标记的构造函数参数
                foreach (var cotr in type.getconstructors().where(c => c.isdefined(typeof(linjectionconstructorattribute), true)))
                {
                    var paraarray = cotr.getparameters();//获取参数数组
                    if (paraarray.length == 0)
                    {
                        return activator.createinstance(type);
                    }

                    list<object> listpara = new list<object>();
                    foreach (var para in paraarray)
                    {
                        string parakey = para.parametertype.fullname;//参数类型名称
                                                                     //从字典中取出缓存的目标对象并创建对象
                        type paratargettype = (type)containertypedictionary[parakey];
                        object opara = createtype(paratargettype);//递归
                        listpara.add(opara);
                    }
                    return activator.createinstance(type,listpara.toarray());
                }

                return activator.createinstance(type);
            }
            else
            {
                //没有标记特性则使用参数最多的构造函数
                var ctor = ctorarray.orderbydescending(c => c.getparameters().length).firstordefault();
                var paraarray = ctor.getparameters();//获取参数数组
                if (paraarray.length == 0)
                {
                    return activator.createinstance(type);
                }

                list<object> listpara = new list<object>();
                foreach (var para in paraarray)
                {
                    string parakey = para.parametertype.fullname;//参数类型名称
                                                                 //从字典中取出缓存的目标对象并创建对象
                    type paratargettype = (type)containertypedictionary[parakey];
                    object opara = createtype(paratargettype);//递归
                    listpara.add(opara);
                }
                return activator.createinstance(type, listpara.toarray());
            }
        }

这里说下为什么用到递归,在我们项目中使用会有层层依赖的关系。比如我这里animal依赖于dog只有一层依赖,如果gog又依赖于猫、猫依赖于鱼。。。(当然这里只是打个比方)

因为我们不知道具体有几层依赖,所以使用了递归的方法,直到将所有依赖的对象得到后再创建实例。

然后我们再来测试

container container = new container();
container.resgistertype<ianimal, animal>();
container.resgistertype<idog, dog>();
ianimal animal= container.rerolve<ianimal>();

注意,如果测试标记特性的一定不要忘了在构造函数上标记特性,然后我们会发现最终也可以得到animal对象。

 

然后,创建对象这一块我们先告一段落。接下来进行生命周期管理。

一般的ioc容器都支持三种类型:transient每次都得到一个新的对象、scoped同一个域(或者请求、线程)中使用同一个对象、singleton整个程序生命周期都使用同一实例对象。

那按照我们以上的代码怎么才能实现生命周期管理呢?我是这么想的:既然创建对象的工作都是由我容器来做了,那么我们在创建完对象之后能不能像注册类型一样将对象保存起来呢?

所以我这里使用了简单的字典来存储对象实例,然后通过判断使用的哪一种生命周期来返回新的对象或是直接返回字典里的对象。直接改造上面的代码了:

/// <summary>
        /// 根据提供的类型创建类型实例并返回
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private object createtype(type type)
        {
            var ctorarray = type.getconstructors();
            if (ctorarray.count(c => c.isdefined(typeof(linjectionconstructorattribute), true)) > 0)
            {
                //获取带特性标记的构造函数参数
                foreach (var cotr in type.getconstructors().where(c => c.isdefined(typeof(linjectionconstructorattribute), true)))
                {
                    var paraarray = cotr.getparameters();//获取参数数组
                    if (paraarray.length == 0)
                    {
                        //return activator.createinstance(type);
                        return getsocpe(type);
                    }

                    list<object> listpara = new list<object>();
                    foreach (var para in paraarray)
                    {
                        string parakey = para.parametertype.fullname;//参数类型名称
                                                                     //从字典中取出缓存的目标对象并创建对象
                        type paratargettype = (type)containertypedictionary[parakey];
                        object opara = createtype(paratargettype);//递归
                        listpara.add(opara);
                    }
                    //return activator.createinstance(type,listpara.toarray());
                    return getsocpe(type, listpara.toarray());
                }

                return getsocpe(type);
                //return activator.createinstance(type);
            }
            else
            {
                //没有标记特性则使用参数最多的构造函数
                var ctor = ctorarray.orderbydescending(c => c.getparameters().length).firstordefault();
                var paraarray = ctor.getparameters();//获取参数数组
                if (paraarray.length == 0)
                {
                    //return activator.createinstance(type);
                    return getsocpe(type);
                }

                list<object> listpara = new list<object>();
                foreach (var para in paraarray)
                {
                    string parakey = para.parametertype.fullname;//参数类型名称
                                                                 //从字典中取出缓存的目标对象并创建对象
                    type paratargettype = (type)containertypedictionary[parakey];
                    object opara = createtype(paratargettype);//递归
                    listpara.add(opara);
                }
                return getsocpe(type, listpara.toarray());
                //return activator.createinstance(type, listpara.toarray());
            }
        }
        private object getsocpe(type type, params object[] listpara)
        {
            if (_scopetype == (int)scope.singleton)
            {
                return gettypesingleton(type, listpara);
            }
            else if (_scopetype == (int)scope.transient)
            {
                return gettypetransient(type, listpara);
            }
            else
            {
                return gettypescoped(type, listpara);
            }
        }

        #region 生命周期
        /// <summary>
        /// 设置获取实例对象生命周期为singleton
        /// </summary>
        /// <param name="type"></param>
        /// <param name="listpara"></param>
        /// <returns></returns>
        private object gettypesingleton(type type, params object[] listpara)
        {
            if (containerexampledictionary.containskey(type.fullname))
            {
                lock (locker)
                {
                    if (containerexampledictionary.containskey(type.fullname))
                    {
                        return containerexampledictionary[type.fullname];
                    }
                }
            }

            if (listpara.length == 0)
            {
                var example = activator.createinstance(type);
                containerexampledictionary.add(type.fullname, example);
                return example;
            }
            else
            {
                var example = activator.createinstance(type, listpara.toarray());
                containerexampledictionary.add(type.fullname, example);
                return example;
            }
        }

        /// <summary>
        /// 设置获取实例对象生命周期为transient
        /// </summary>
        /// <param name="type"></param>
        /// <param name="listpara"></param>
        /// <returns></returns>
        private object gettypetransient(type type, params object[] listpara)
        {
            if (listpara.length == 0)
            {
                var example = activator.createinstance(type);
                //containerexampledictionary.add(type.fullname, example);
                return example;
            }
            else
            {
                var example = activator.createinstance(type, listpara.toarray());
                //containerexampledictionary.add(type.fullname, example);
                return example;
            }
        }

        /// <summary>
        /// 设置获取实例对象生命周期为scoped
        /// </summary>
        /// <param name="type"></param>
        /// <param name="listpara"></param>
        /// <returns></returns>
        private object gettypescoped(type type, params object[] listpara)
        {
            var pid = system.threading.thread.currentthread.managedthreadid;
            if (containerexampledictionary.containskey(type.fullname + pid))
            {
                lock (locker)
                {
                    if (containerexampledictionary.containskey(type.fullname + pid))
                    {
                        return containerexampledictionary[type.fullname + pid];
                    }
                }
            }

            if (listpara.length == 0)
            {
                var example = activator.createinstance(type);
                containerexampledictionary.add(type.fullname + pid, example);
                return example;
            }
            else
            {
                var example = activator.createinstance(type, listpara.toarray());
                containerexampledictionary.add(type.fullname + pid, example);
                return example;
            }
        }
        #endregion
private static dictionary<string, object> containerexampledictionary = new dictionary<string, object>();
        private static int _scopetype;
        private static readonly object locker = new object();
        public int scopetype
        {
            get
            {
                return _scopetype;
            }
            set
            {
                _scopetype = value;
            }
        }
        public enum scope
        {
            singleton = 0,
            transient = 1,
            scoped = 2
        }

然后调用的时候先声明下要使用的声明周期类型就行啦

container container = new container();
container.scopetype = (int)container.scope.singleton;
container.resgistertype<ianimal, animal>();
container.resgistertype<idog, dog>();
ianimal animal= container.rerolve<ianimal>();

说下三种生命周期管理的实现:

transient:则可以直接创建一个实例

scoped:使用的是同一个线程内使用同一个对象实例,使用var pid = system.threading.thread.currentthread.managedthreadid;获取线程id来判断的

singleton:这种则只需一个单例模式获取就好了

 

到这里就先告一段落了,以上只是一个简单实现,代码还有需改进的地方以及可以扩展的功能,欢迎提意见指出错误。同时代码已上传gighub,还有不懂的可以参考下代码。

 源码地址:https://github.com/liangchengxuyuan/ioccontainer

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网