反射 + 配置文件 实现IOC容器

IOC实现:


IOC容器我们仅仅停留在知道上是不行的,我们要动手做印象对更深刻,那么我给大家看一个代码,看看代码中IOC容器的实现。


代码实现:


创建一个类库:


解决方案的类库建立:




创建一个实体类:User:


<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Text;

namespace Spring.Demo.Model
{
    /// <summary>
    /// 用户类
    /// </summary>
    public class Users
    {
        /// <summary>
        /// 编号
        /// </summary>
        private int _oid;
        public int Oid
        {
            get { return _oid; }
            set { _oid = value; }
        }

        /// <summary>
        /// 姓名
        /// </summary>
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        /// <summary>
        /// 性别
        /// </summary>
        private string _sex;
        public string Sex
        {
            get { return _sex; }
            set { _sex = value; }
        }

        /// <summary>
        /// 年龄
        /// </summary>
        private int _age;
        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
    }
}</span>

创建IUsers的接口:


<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Text;
namespace Spring.Demo.Service
{
    public interface IUsers
    {
        /// <summary>
        /// 返回用户的详细信息的方法
        /// </summary>
        /// <returns></returns>
        string GetUserInfo();
    }
}
</span>

创建一个实现IUsers接口的实现类:


<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Text;
using Spring.Demo.Service;
using Spring.Demo.Model;

namespace Spring.Demo.Compontext
{
    public class UsersCompontents : IUsers
    {
        public UsersCompontents()
        { }

        #region 获取用户信息
        public string GetUserInfo()
        {
            Users user = new Users();
            user.Oid = 1;
            user.Name = "Beniao";
            user.Sex = "Boy";
            user.Age = 25;

            return string.Format("编号:{0}--->姓名:{1}--->性别:{2}--->年龄:{3}",
                user.Oid,
                user.Name,
                user.Sex,
                user.Age);
        }
        #endregion
    }
}</span>

创建测试类:


<span style="font-size:18px;">using ITOO.Library.Core.AOP;
using Spring.Context;
using Spring.Demo.Service;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace Sping.Demo.SimpleTest
{
    class Program
    {
        static void Main(string[] args)
        {

            IUsers studentChangeBll = SpringHelper.GetObject<IUsers>("Users");

            Console.WriteLine(studentChangeBll.GetUserInfo());
            Console.Read();
        }
    }
}</span>

在控制台程序中创建一个配置文件:


<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="spring">
      <section name="context"
               type="Spring.Context.Support.ContextHandler, Spring.Core"/>
      <section name="objects"
               type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
    </sectionGroup>
  </configSections>
  <spring>
    <context>
      <resource uri="config://spring/objects"/>
    </context>
    <objects xmlns="http://www.springframework.net">
      <!--这的配置根据实际的程序来的,UsersCompontents是程序集Spring.Demo.Compontext下的一个类-->
      <object name="Users"
              type="Spring.Demo.Compontext.UsersCompontents,Spring.Demo.Compontext"  singleton="false" >
      </object>
    </objects>
  </spring>
</configuration></span>

运行后,发现SpringHelper却小引用。我们一般写代码中我们是这样写的:


<span style="font-size:18px;">//从config文件中取得程序集信息
IApplicationContext context = ConfigurationManager.GetSection("spring/context")
                               as IApplicationContext;
//调用方法
//Users为config文件里的配置节
//<object name="Users"       
//        type="Spring.Demo.Compontext.UsersCompontents,Spring.Demo.Compontent">
//</object>
IUsers user = context.GetObject("Users") as IUsers;</span>

这样我们就可以从配置文件中将对象取出来,但是我们都不想在代码中有多余的代码,不能每一次new对象的时候,我们都要写一遍这句话:IApplicationContext context = ConfigurationManager.GetSection("spring/context") as IApplicationContext;这样就增加了我们维护代码的成本,因此,我们将这句话封装起来,封装的代码是这样的:


创建一个类:SpringHelper:


<span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Context;
using Spring.Context.Support;

namespace ITOO.Library.Core.AOP
{
    public class SpringHelper
    {
        /// <summary>
        /// Spring容器上下文
        /// </summary>
        private static IApplicationContext SpringContext
        {
            get
            {
                return ContextRegistry.GetContext();
            }
        }


        /// <summary>
        /// 获取配置文件 配置的 对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objName"></param>
        /// <returns></returns>
        public static T GetObject<T>(string objName) where T : class
        {
            return (T)SpringContext.GetObject(objName);
        }
    }
}


</span>

以上的代码我们就可以将每次读取配置文件中的那句话去掉了,我们直接就可以写这样一句话就可以了:IUsers studentChangeBll = SpringHelper.GetObject<IUsers>("Users");


这里体现了封装的重要性,先前我在做AOP的时候,我的师傅看到了类似这样的代码的时候,他就跟我讨论过这个问题,我当时懵懵懂懂,没有进行下一步的行动,现在想想,问题出现在我根本没有动手去做,或者知识没有深入到那个层次,认识这个知识的方面没有那么深。所有问题,都要动手去做才行。


总结:


我们从上面的实践到分析之后,我们发现其实我们看似是新的东西,其实我们已经学习过了,就像IOC容器一样,我们学习过了反射和配置文件,我们发现其实IOC容器不就是反射和配置文件来实现的吗,反射和配置文件是我们在大话设计模式中就已经学习到了的东西,这都不是新的东西。一个看似复杂的东西,都是有简单的东西来组装成的,我们知道这个,就不会对新的东西有畏惧感了。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 26
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值