Spring.Net學習筆記一(IOC第一個執行個體)

來源:互聯網
上載者:User

標籤:

     最近,即將要去新加坡出差,所以在簽證這段時間比較空閑,所以想起學習點東西,由於接觸過Unity,Autofac等IOC容器,沒有接觸Spring.Net,故想揭開它神奇的面紗。任何東西都是紙老虎!

     首先還是來一個簡單建立對象的例子。

     第一步:我現在推薦使用Nuget來下載最新的程式集,這個能及時更新,而且能自動引起程式集所依賴的項。

     第二步:增加設定檔,按照Sprint.Net手冊增加設定檔。

     第三步,進行測試回合。

     代碼如下:

      建立的類庫代碼:Dao

      

 1 namespace Dao 2 { 3     public interface IPersonDao 4     { 5         void Save(); 6     } 7     public class PersonDao : IPersonDao 8     { 9         public void Save()10         {11             Console.WriteLine("儲存 Person");12         }13     }14 15     public class PersonDao1 : IPersonDao16     {17         public void Save()18         {19             Console.WriteLine("儲存 Person1");20         }21     }22 }

  設定檔代碼:

  

 1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3   <configSections> 4     <sectionGroup name="spring"> 5       <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/> 6       <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /> 7     </sectionGroup> 8   </configSections> 9   <spring>10     <context>11       <!--容器配置-->12       <resource uri="config://spring/objects"/>13     </context>14     <objects xmlns="http://www.springframework.net">15       <!--這裡放容器裡面的所有節點-->16       <description>An  example that demonstrates simple IoC features.</description>17       <!--name 必須要唯一的,type=類的全名稱,所在的程式集-->18       <object name="PersonDao" type="Dao.PersonDao1, Dao">19       </object>20     </objects>21   </spring>22   <startup>23     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />24   </startup>25 </configuration>

入口函數代碼:

 1 using Dao; 2 using Spring.Context; 3 using Spring.Context.Support; 4 using System; 5 using System.Collections.Generic; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 10 namespace MovieApp11 {12     class Program13     {14         static void Main(string[] args)15         {16             IApplicationContext ctx = ContextRegistry.GetContext();17             IPersonDao dao = ctx.GetObject("PersonDao") as IPersonDao;18             if (dao != null)19             {20                 dao.Save();21                 Console.WriteLine("我是IoC方法");22                 Console.ReadKey();23             }24         }25     }26 }

 

 運行很良好,出來想要的結果!

     

Spring.Net學習筆記一(IOC第一個執行個體)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.