DI spring.net简单使用

IOC或DI  spring.net简单使用

一.spring.net是什么?

二.spring.net的作用:

三.spring.net的Demo:

1.引用spring.net程序集:

nuget或者找到spring.net的程序集即可

2.创建帮助类:

 public class SpringHelper
    {
        #region Spring容器上下文 +IApplicationContext SpringContext
        /// <summary>
        /// Spring容器上下文
        /// </summary>
        private static IApplicationContext SpringContext
        {
            get
            {
                return ContextRegistry.GetContext();
            }
        }
        #endregion

        #region 获取配置文件配置的对象 +T GetObject<T>(string objName) where T : class
        /// <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);
        }
        #endregion
    }

3.配置:

为了不让web.config文件不是很大,于是把他们拆分;

在ui层项目中新建一个文件夹:Config,然后在他里面创建几个xml文件,xml就是spring.net的配置,如下图:

web.config中配置:

在<configuration>节点下配置如下图:

  <configSections>
    <sectionGroup name="spring">
      <!--配置解析Spring块的对象-->
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
      <!--配置解析Spring存放对象的容器集合-->
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
    </sectionGroup>
  </configSections>
  <!--Spring.Net节点配置-->
  <spring>
    <context>
      <!--容器配置-->
      <!--<resource uri="config://spring/objects"/>-->
      <!--xml文件方式,更改属性,复制到输出目录:始终复制-->
      <resource uri="~/Config/dal.xml"/>
      <resource uri="~/Config/service.xml"/>
      <resource uri="~/Config/controllers.xml"/>
    </context>
  </spring>

xml配置如下:(属性注入的方式)
controllers.xml配置:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
  <object type="ZLP.MVC.Controllers.HomeController, ZLP.MVC.Controllers" singleton="false" >
    <!--<property name="UserBLL" ref="UserBLL" />-->
  </object>
</objects>

service.xml配置:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
  <object name="UserBLL" type="ZLP.BLL.UserBLL, ZLP.BLL" singleton="false">
    <!--<property name="UserDAL" ref="UserDAL" />-->
  </object>
</objects>

dal.xml配置:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
  <object name="UserDAL" type="ZLP.DAL.UserDAL, ZLP.DAL" singleton="false"></object>
</objects>

2.获取对象:

 IUserBLL UserBLL = SpringHelper.GetObject<IUserBLL>("UserBLL");


四.完整测试Demo:(vs2017开发的)

猜你喜欢

转载自www.cnblogs.com/zlp520/p/10605551.html
今日推荐