Spring.Net simple IoC example

Here is another IoC example using Spring.Net similar to the Movie Finder example taken from Martin Fowler’s article.
This example return a list of all employees that match the specified department and demonstrates how the Spring.Net IoC container can be used to supply an appropriate IEmployeeService implementation to an arbitrary EmployeeService instance.

Create new console application project called EmployeeFinder, and add the following references to use in this example.

1. Common.Logging
2. Common.Logging.Log4Net
3. log4net
4. Spring.Core
5. System

Create Employee value object class.

Employee.cs
  1. namespace Net.Depanca.EmployeeService
  2. {
  3.     public class Employee
  4.     {
  5.         private string name;
  6.         private string department;
  7.  
  8.         public Employee(string name, string department) {
  9.             this.name = name;
  10.             this.department = department;
  11.         }
  12.  
  13.         public string Name {
  14.             get { return name; }
  15.             set { this.name = value; }
  16.         }
  17.  
  18.         public string Department {
  19.             get { return department; }
  20.             set { this.department = value; }
  21.         }
  22.     }
  23. }

Application entry point :

Program.cs
  1. using System;
  2. using System.Collections.Specialized;
  3. using Common.Logging;
  4. using Common.Logging.Log4Net;
  5. using Spring.Context;
  6. using Spring.Context.Support;
  7. using Spring.Objects.Factory.Config;
  8. using Spring.Objects.Factory.Support;
  9. using Spring.Objects.Factory.Xml;
  10.  
  11. namespace Net.Depanca.EmployeeService
  12. {
  13.     public class Program
  14.     {
  15.         private static readonly ILog LOG = LogManager.GetLogger(typeof(Program));
  16.  
  17.         [STAThread]
  18.         public static void Main() {
  19.             try {
  20.                 IApplicationContext ctx = ContextRegistry.GetContext();
  21.                 EmployeeLister employeeLister = (EmployeeLister)ctx.GetObject("MyEmployeeLister");
  22.                 Employee[] employees = employeeLister.EmployeeByDepartment("Finance");
  23.                 LOG.Debug("Searching for employee….");
  24.  
  25.                 foreach(Employee employee in employees){
  26.                     LOG.Debug(string.Format("Employee name = {0}, Department = {1}", employee.Name, employee.Department));
  27.                 }
  28.  
  29.                 LOG.Debug("Employee service done….");
  30.  
  31.             }catch(Exception e){
  32.                 LOG.Debug("Employee services is broken….");
  33.             }finally{
  34.                 Console.WriteLine();
  35.                 Console.WriteLine(" - Press return to exit! - ");
  36.                 Console.ReadLine();
  37.             }
  38.         }
  39.     }
  40. }

Open the App.config file then fill it with the code bellow

App.config
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3.   <configSections>
  4.     <sectionGroup name="common">
  5.       <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/>
  6.     </sectionGroup>
  7.     <sectionGroup name="spring">
  8.       <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
  9.       <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
  10.     </sectionGroup>
  11.     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  12.   </configSections>
  13.  
  14.   <common>
  15.     <logging>
  16.       <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net">
  17.         <arg key="configType" value="INLINE" />
  18.       </factoryAdapter>      
  19.     </logging>
  20.   </common>
  21.  
  22.   <spring>
  23.     <context>
  24.       <resource uri="config://spring/objects" />
  25.     </context>
  26.  
  27.     <objects xmlns="http://www.springframework.net">
  28.       <description>An example that demonstrates simple IoC features.</description>
  29.  
  30.       <object id="MyEmployeeLister" type="Net.Depanca.EmployeeService.EmployeeLister, Net.Depanca.EmployeeService">
  31.         <property name="EmployeeService" ref="AnotherEmployeeFinder" />
  32.       </object>
  33.  
  34.       <object id="MyEmployeeFinder" type="Net.Depanca.EmployeeService.SimpleEmployeeFinder, Net.Depanca.EmployeeService" />
  35.  
  36.       <object id="AnotherEmployeeFinder" type="Net.Depanca.EmployeeService.ColonDelimiterEmployeeFinder, Net.Depanca.EmployeeService">
  37.         <constructor-arg index="0" value="employee.txt" />
  38.       </object>
  39.  
  40.       <object type="Spring.Objects.Factory.Attributes.RequiredAttributeObjectPostProcessor, Spring.Core"/>
  41.            
  42.     </objects>
  43.   </spring>
  44.  
  45.   <log4net>
  46.     <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
  47.       <layout type="log4net.Layout.PatternLayout">
  48.         <conversionPattern value="%-5level - %message%newline" />
  49.       </layout>
  50.     </appender>
  51.  
  52.     <root>
  53.       <level value="DEBUG" />
  54.       <appender-ref ref="ConsoleAppender" />
  55.     </root>
  56.  
  57.     <logger name="Net.Depanca.EmployeeService">
  58.       <level value="DEBUG" />
  59.     </logger>
  60.  
  61.     <logger name="Spring">
  62.       <level value="INFO" />      
  63.     </logger>
  64.    
  65.   </log4net>
  66. </configuration>

Now create the IEmployeeService interface

IEmployeeService.cs
  1. using System.Collections;
  2.  
  3. namespace Net.Depanca.EmployeeService
  4. {
  5.     public interface IEmployeeService
  6.     {
  7.         IList FindAll();
  8.     }
  9. }

Create the implementation class that will load the user information from file or from embeded resource in the application.

SimpleEmployeeFinder.cs
  1. using System.Collections;
  2.  
  3. namespace Net.Depanca.EmployeeService
  4. {
  5.     public class SimpleEmployeeFinder : IEmployeeService
  6.     {
  7.         private ArrayList list = new ArrayList();
  8.  
  9.         public SimpleEmployeeFinder() {
  10.             InitList();
  11.         }
  12.  
  13.         public void AddEmployee(Employee employee) {
  14.             list.Add(employee);
  15.         }
  16.  
  17.         public IList FindAll() {
  18.             return new ArrayList(list);
  19.         }
  20.  
  21.         private void InitList() {
  22.             this.list.Add(new Employee("obelix", "Service"));
  23.         }
  24.     }
  25. }

Here is another IEmployeeService implementation that take the information from file.

ColonDelimiterEmployeeFinder.cs
  1.  
  2. using System.Collections;
  3. using System.IO;
  4. using System;
  5.  
  6. namespace Net.Depanca.EmployeeService
  7. {
  8.     public class ColonDelimiterEmployeeFinder : IEmployeeService
  9.     {
  10.         private static readonly char[] Delimiter = new char[]{':'};
  11.  
  12.         private FileInfo employeeFile;
  13.         private IList employees;
  14.  
  15.         public ColonDelimiterEmployeeFinder(FileInfo file) {
  16.  
  17.                 EmployeeFile = file;
  18.  
  19.         }
  20.  
  21.         public FileInfo EmployeeFile{
  22.             get { return employeeFile; }
  23.             set
  24.             {
  25.                     employeeFile = value;
  26.                     if (employeeFile != null &amp;&amp; employeeFile.Exists)
  27.                     {
  28.                         InitList();
  29.                     }
  30.  
  31.             }
  32.         }
  33.  
  34.         public IList FindAll() {
  35.             return employees;
  36.         }
  37.  
  38.         private void InitList() {
  39.             employees = new ArrayList();
  40.             using(StreamReader reader = EmployeeFile.OpenText()){
  41.                 string line = null;
  42.                 while((line = reader.ReadLine()) != null){
  43.                     string[] tuple = line.Split(Delimiter);
  44.                     Employee employee = new Employee(tuple[0], tuple[1]);
  45.                     employees.Add(employee);
  46.                 }
  47.             }
  48.         }
  49.     }
  50. }
EmployeeLister.cs
  1.  
  2. using System.Collections;
  3. using Spring.Objects.Factory.Attributes;
  4.  
  5. namespace Net.Depanca.EmployeeService
  6. {
  7.     public class EmployeeLister
  8.     {
  9.         private IEmployeeService employeeService;
  10.  
  11.         public EmployeeLister() {
  12.         }
  13.  
  14.         [Required]
  15.         public IEmployeeService EmployeeService {
  16.             get { return employeeService; }
  17.             set { employeeService = value; }
  18.         }
  19.  
  20.         public Employee[] EmployeeByDepartment(string department) {
  21.  
  22.             IList allList = employeeService.FindAll();
  23.             IList employees = new ArrayList();
  24.  
  25.             foreach(Employee employee in allList){
  26.                 if((employee.Department).Equals(department)){
  27.                     employees.Add(employee);
  28.                 }
  29.             }
  30.  
  31.             return (Employee[])ArrayList.Adapter(employees).ToArray(typeof(Employee));
  32.         }
  33.     }
  34. }

Create employee.txt file used by ColonDelimiterEmployeeFinder.cs to find the related employee.

employee.txt
  1. Patric:Finance
  2. Spongebob:Finance
  3. Asterix:service
  4. Obelix:service

Now to test the IoC feature.
Run the application. You’ll get a result similar to the figure bellow.

Result using ColonDelimiterEmployeeFinder

change the ref value “AnotherEmployeeFinder” in the App.config file to “MyEmployeeFinder”. Then run the application. You’ll get the following result in your window.

Result using SimpleEmployeeFinder

You see from the above result. The 1st result take the employee data from the employee.txt file. And the 2nd result using the hardcoded data in the SimpleEmployeeFinder.cs.

Download example

 

Related Articles

Leave a Reply