)

王朝学院·作者佚名  2016-05-16
窄屏简体版  字體: 小  |  中  |  大  |  超大  

sPRing.net (1) 概念-控制反转(又名依赖注入)Spring.net 作为一个应用程序框架,在构建企业级.net应用程序提供了很多灵活而又丰富的功能(如:依赖注入,aop,数据访问抽象,asp.net 扩展)。

控制反转:Inversion of Control:简称IoC :是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体,将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。

个人理解:根据面向对象中对象的父子继承,接口或抽象的实现等,对持有关系的对象的实例化进行控制。

实例:有一只宠物:

public interface Pet { string name { get; set; } void bark(); }

小狗:

public class Dog : Pet { public string name { get; set; } public void bark() { Console.WriteLine("汪汪汪汪汪汪汪汪汪..."); } }

人:

public class Person { public string name { get; set; } public Pet pet { get; set; } }

一个简单的spring框架:项目引用:spring.core --整个框架的基础,实现了依赖注入的功能

Spring.AOP--提供面向方面编程(aop)的支持

Spring.Data--a定义了一个抽象的数据访问层,可以跨越各种数据访问技术(从ADO.NET到各种orm)进行数据访问。

项目配置文件: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="file://objects.xml"></resource> </context> <objects xmlns="http://www.springframework.net"> </objects> </spring></configuration>

objects.xml 属性为始终复制,不然上面配置的<resource uri="file://objects.xml"></resource>找不到。

<?xml version="1.0" encoding="utf-8" ?><objects xmlns="http://www.springframework.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd"> <object id="person" type="SpringDemo.Person,SpringDemo" singleton="true" > <property name="pet" ref="dog" ></property> <property name="name" value="Yahue"></property> </object> <object id="dog" type="SpringDemo.Dog,SpringDemo" singleton="true"> <property name="name" value="旺财"></property> </object></objects>

控制台程序中:

static void fistIoC(){Person p = ctx.GetObject("person") as Person; Console.WriteLine(p.pet.name);Console.WriteLine("-------------------------");}

调用:

static IapplicationContext ctx = ContextRegistry.GetContext(); static void Main(string[] args) { fistIoC(); Console.ReadLine(); }

控制台输出:

旺财

-------------------------ok 第一个ioc例子就这样结束了。简单的说:spring.net 就像是个实例化工厂,对实例对象注入,实例对象进行属性的赋值等。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航