IOC或DI spring.net簡單使用程序員
一.spring.net是什麼?web
Spring 框架本是 Java 平臺上一個應用很是多的、開源的框架。雖然語言是固定的,可是好的方法應該是通用的,因而 Spring 框架 就被程序員從 Java 平臺搬遷到了 .NET 平臺。spring
二.spring.net的做用:框架
spring框架做用是控制反轉及依賴注入;測試
三.spring.net的Demo:ui
1.引用spring.net程序集:spa
nuget或者找到spring.net的程序集便可.net
2.建立幫助類:code
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.配置:xml
爲了避免讓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開發的)
https://download.csdn.net/download/zhang1096646030/11064414