IOC:Inversion Of Control
控制翻轉:就是創建對象的權利由開發人員自己控制,轉換到了由容器來控制
我用的是winform里的一個按鍵來觸發的
首先要引入兩個SPRing.net的dll文件Common.Logging.dll 和Spring.Core.dll
private void button1_Click(object sender, EventArgs e) { IapplicationContext ctx = ContextRegistry.GetContext(); UserInfoService userInfo = (UserInfoService)ctx.GetObject("UserInfoService"); userInfo.Show(); }
public class UserInfoService { public UserInfo user { get; set; }
//構造函數 public UserInfoService(int age) { Age = age; } public int Age { get; set; } public string serverName { get; set; } public void Show() { Console.WriteLine("OK2------"+serverName); Console.WriteLine("Age=" + Age); Console.WriteLine("User=" + user.uName); } }}
//user類型
namespace SpringDemo{ public class UserInfo { public string uName { get; set; } }}
之后就直接在app.config里注入代碼就可以了
<?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"/> <resource uri="file://Servicess.xml"/> </context> <objects xmlns="http://www.springframework.net"> <description>An example that demonstrates simple IoC features.</description> <object name="UserInfoService" type="SpringDemo.UserInfoService, SpringDemo "> <constructor-arg name="age" value="18"/>//--------構造函數注入 <property name="serverName" value="yang"/>//------------屬性注入 <property name="user" ref="UserInfo"/> </object> <object name="UserInfo" type="SpringDemo.UserInfo, SpringDemo ">//-----user類型的注入 <property name="uName" value="yang2"/> </object> </objects> </spring></configuration>
然后調試就完美輸出了
OK2---------yang
Age=18
User=yang2
從現在開始一點點進步
新聞熱點
疑難解答