Spring. Net learning notes (2)-dependency injection, spring.net learning notes
I. Development Environment
Operating System: Win10
Compiler: VS2013
Framework Version:. net 4.5
Spring version: 1.3.1
Ii. Assembly
Spring. Core. dll
Common. Loggin. dll
Iii. Project Structure
Namespace SpringNetIoc. IScene {public interface IBall {void DoSport ();}}2. Create two classes that implement the IBall Interface
Namespace SpringNetIoc. Scene {public class Basketball: IBall {public void DoSport () {Console. WriteLine ("Basketball ");}}}
Namespace SpringNetIoc. Scene {public class Tennis: IBall {public void DoSport () {Console. WriteLine (" ");}}}
3. Create a Person class
namespace SpringNetIoc.Role{ public class Person { public IBall Ball { get; set; } public void Hobby() { Ball.DoSport(); } }}
4. Configure Spring.net
<?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 xmlns="http://www.springframework.net"> <context> <resource uri="config://spring/objects"></resource> </context> <objects xmlns="http://www.springframework.net"> <object name="basketball" type="SpringNetIoc.Scene.Basketball,SpringNetIoc"></object> <object name="tennis" type="SpringNetIoc.Scene.Tennis,SpringNetIoc"></object> <object name="person" type="SpringNetIoc.Role.Person,SpringNetIoc"> <!--<property name="Ball" ref="basketball"></property>--> <property name="Ball" ref="tennis"></property> </object> </objects> </spring> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup></configuration>
5. output results in the console
namespace SpringNetIoc{ class Program { static void Main(string[] args) { IApplicationContext context = ContextRegistry.GetContext(); Person person = context.GetObject("person") as Person; person.Hobby(); Console.Read(); } }}
V. program description
To some extent, the coupling problem between Person and IBall is solved, but coupling is not completely solved, but only put in xml file. This dependency is formed by a container as needed, that is, the required interface implementation is injected into the class that requires it. The IoC mode can be seen as container + factory. However, all the objects to be generated in this large factory are defined in the xml file.
6. References
Http://www.cnblogs.com/GoodHelper/archive/2009/10/26/SpringNET_DI.html