标签:切面 UI 创建对象 nbsp sim str rgs core cat
在我们日常项目开发中为了降低项目各个层支之间的耦合度,我们使用开源框架Spring.Net来创建对象实例。
注:Spring.Net是一个容器,用来创建对象,
Spring.Net的核心IOC(控制反转)、DI(依赖注入)、AOP(面向切面编程)
作用:IOC:创建对象实例(由容器自己去new一个对象出来)、DI:创建对象实例时,为这个对象注入属性值。
代码实现:
1、使用标准的配置初始容器(使用配置创建容器)
1)、使用配置文件创建容器
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"/> ---对应下面<context>节,用来指定另一个XML配置文件的路径 6 <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /> ---对应着下面<object>节,配置要创建实例的类 7 </sectionGroup> 8 </configSections> 9 <spring> 10 <context> 11 <resource uri="config://spring/objects"/> 12 <resource uri="file://service.xml"/> 13 </context> 14 <objects xmlns="http://www.springframework.net"> 15 <!--<description>An example that demonstrates simple IoC features.</description> 16 <object name="UserInfoService" type="Spring.Net.Demo.UserInfoService,Spring.Net.Demo"> ---name="要创建的类的实例名: type="要创建实例的命名空间.类名,程序集" 17 <property name="Name" value="张三"/> ---DI的使用,name="类中的属性名",value="要给属性赋的值" 18 <property name="Person" ref="Person"/> ---UserInfoService中有一个Person类型的属性Person,给属性Person赋值 19 </object> 20 <object name="Person" type="Spring.Net.Demo.Person, Spring.Net.Demo"> ---添加一个<object>节,实例化Person类, 21 <property name="Age" value="20"/> --使用依赖注入给Person类的Age属性赋值 22 </object>--> 23 </objects> 24 </spring> 25 </configuration>
2、在项目中引入程序集体
在UI层创建业务层对象,使用Spring.Net来创建来实现解耦,点击Button按钮创建UserInfoServices对象,赋值给他的接口IUserInfoService
1 private void button1_Click(object sender, EventArgs e) 2 { 3 IApplicationContext ctx = ContextRegistry.GetContext(); //创建容器. 4 IUserInfoService lister = (IUserInfoService)ctx.GetObject("UserInfoService"); 5 MessageBox.Show(lister.ShowMsg()); 6 }
IUserInfoService接口
1 public interface IUserInfoService 2 { 3 string ShowMsg(); 4 }
UserInfoService类
public class UserInfoService : IUserInfoService { public string Name { get; set; } public Person person { get; set; } public string ShowMsg() { return "Hello Spring.Net"+Name+","+person.Age; } }
Person类
1 public class Person 2 { 3 public int Age { get; set; } 4 }
标签:切面 UI 创建对象 nbsp sim str rgs core cat
原文地址:https://www.cnblogs.com/Jenkin/p/9135245.html