Dependency Injection Pattern in Java using Spring (part 4)

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.app</groupId>
    <artifactId>my-module</artifactId>
    <version>1</version>
 
    <dependencies>
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <defaultGoal>compile</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.5.1</version>
                <executions>
                    <execution>
                        <id>copy1</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>.\lib</outputDirectory>
                            <!-- other configurations here -->
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

IValidator.java

package com.compare;

public interface IValidator<T> {
    boolean isValid(T instance);
}

GreaterThanFourValidator.java

package com.compare;

public class GreaterThanFourValidator implements IValidator<Integer> {

    @Override
    public boolean isValid(Integer instance) {
        return instance > 4;
    }
}

IntegerOnlyValidator.java

package com.compare;

public class IntegerOnlyValidator implements IValidator<String>{

    @Override
    public boolean isValid(String instance) {
        int i = 0;
        boolean b = false;
        try {
            Integer.parseInt(instance);
            b = true;
        }
        catch (Exception e)
        {
        }
        return b;
    }
}

GreaterThanFourValidatorTest.java

package com.compare;

public class GreaterThanFourValidatorTest {
    IValidator<Integer> validator;

    public IValidator<Integer> getValidator() {
        return validator;
    }

    public void setValidator(IValidator<Integer> validator) {
        this.validator = validator;
    }
}

IntegerOnlyValidatorTest.java

package com.compare;

public class IntegerOnlyValidatorTest {
    IValidator<String> validator;

    public IValidator<String> getValidator() {
        return validator;
    }

    public void setValidator(IValidator<String> validator) {
        this.validator = validator;
    }
}

Main.java

package com.compare;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        try(ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml")) {
            IntegerOnlyValidatorTest intOnly = (IntegerOnlyValidatorTest) context.getBean("IntegerOnlyTest");
            System.out.println(intOnly.validator.isValid("5554"));
            System.out.println(intOnly.validator.isValid("123ab"));

            GreaterThanFourValidatorTest greater4Only = (GreaterThanFourValidatorTest) context.getBean("GreaterThanFourTest");
            System.out.println(greater4Only.validator.isValid(10));
            System.out.println(greater4Only.validator.isValid(1));
        }
    }
}

bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="GreaterThanFour" class="com.compare.GreaterThanFourValidator" />

    <bean id="IntegerOnly" class="com.compare.IntegerOnlyValidator" />

    <bean id="GreaterThanFourTest" class="com.compare.GreaterThanFourValidatorTest">
        <property name="validator">
            <ref local="GreaterThanFour"/>
        </property>
    </bean>

    <bean id="IntegerOnlyTest" class="com.compare.IntegerOnlyValidatorTest">
        <property name="validator">
            <ref local="IntegerOnly"/>
        </property>
    </bean>
</beans>

Dependency Injection Pattern in Java using Spring (Part 3)

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.app</groupId>
    <artifactId>my-module</artifactId>
    <version>1</version>
 
    <dependencies>
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <defaultGoal>compile</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.5.1</version>
                <executions>
                    <execution>
                        <id>copy1</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>.\lib</outputDirectory>
                            <!-- other configurations here -->
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

IPerson.java

package conferenceRoom;

public interface IPerson {
    String getName();
}

Person.java

package conferenceRoom;

public class Person implements IPerson{
	 
    String name = "default";
 
    public Person(String name)
    {
        this.name = name;
    }
 
    @Override
    public String getName() {
        return name;
    }
}

IConferenceRoom.java

package conferenceRoom;

public interface IConferenceRoom
{
    IPerson[] getPeople();
}

ConferenceRoom.java

package conferenceRoom;

public class ConferenceRoom implements IConferenceRoom {

	IPerson[] people;
	public ConferenceRoom(IPerson[] people)
    {
        this.people = people;
    }
	
	@Override
	public IPerson[] getPeople() {
		return people;
	}

}

Work.java

package conferenceRoom;

public class Work {
	IConferenceRoom conferenceRoom1;
	IConferenceRoom conferenceRoom2;
	
	public IConferenceRoom getConferenceRoom1() {
		return conferenceRoom1;
	}
	public void setConferenceRoom1(IConferenceRoom conferenceRoom1) {
		this.conferenceRoom1 = conferenceRoom1;
	}
	public IConferenceRoom getConferenceRoom2() {
		return conferenceRoom2;
	}
	public void setConferenceRoom2(IConferenceRoom conferenceRoom2) {
		this.conferenceRoom2 = conferenceRoom2;
	}
}

Main.java

package conferenceRoom;

import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class Main {
 
    public static void main(String[] args) {
        try(ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml")) {
            Work work = (Work)context.getBean("Work");
            
            System.out.println("People at conference room 1");
            for(IPerson p : work.getConferenceRoom1().getPeople())
            {
            	System.out.println(p.getName());
            }
            
            System.out.println();
            System.out.println("People at conference room 2");
            for(IPerson p : work.getConferenceRoom2().getPeople())
            {
            	System.out.println(p.getName());
            }
            
            IConferenceRoom outOfTheBlue = (IConferenceRoom)context.getBean("conferenceRoom_OutofTheBlue");
            work.setConferenceRoom2(outOfTheBlue);
            
            System.out.println();
            System.out.println("People at conference room 1");
            for(IPerson p : work.getConferenceRoom1().getPeople())
            {
            	System.out.println(p.getName());
            }
            
            System.out.println();
            System.out.println("People at conference room 2");
            for(IPerson p : work.getConferenceRoom2().getPeople())
            {
            	System.out.println(p.getName());
            }
        }
    }
}

bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <bean id="John" class="conferenceRoom.Person">
        <constructor-arg>
            <value>John</value>
        </constructor-arg>
    </bean>
 
    <bean id="Catherine" class="conferenceRoom.Person">
        <constructor-arg>
            <value>Catherine</value>
        </constructor-arg>
    </bean>
 
     <bean id="Ben" class="conferenceRoom.Person">
        <constructor-arg>
            <value>Ben</value>
        </constructor-arg>
    </bean>

     <bean id="Elizabeth" class="conferenceRoom.Person">
        <constructor-arg>
            <value>Elizabeth</value>
        </constructor-arg>
    </bean>
    
     <bean id="Jennifer" class="conferenceRoom.Person">
        <constructor-arg>
            <value>Jennifer</value>
        </constructor-arg>
    </bean>
    
     <bean id="Michael" class="conferenceRoom.Person">
        <constructor-arg>
            <value>Michael</value>
        </constructor-arg>
    </bean>
    
    <bean id="conference1" class="conferenceRoom.ConferenceRoom">
        <constructor-arg>
            <array value-type="conferenceRoom.IPerson">
            	<ref local="John"/>
            	<ref local="Catherine" />
        	</array>
        </constructor-arg>
    </bean>
    
    <bean id="conference2" class="conferenceRoom.ConferenceRoom">
        <constructor-arg>
            <array value-type="conferenceRoom.IPerson">
            	<ref local="Ben"/>
            	<ref local="Elizabeth" />
        	</array>
        </constructor-arg>
    </bean>
    
    <bean id="conferenceRoom_OutofTheBlue" class="conferenceRoom.ConferenceRoom">
        <constructor-arg>
            <array value-type="conferenceRoom.IPerson">
            	<ref local="Jennifer"/>
            	<ref local="Michael" />
        	</array>
        </constructor-arg>
    </bean>
    
    <bean id="Work" class="conferenceRoom.Work">
        <property name="conferenceRoom1">
        	<ref local="conference1" />
        </property>
        <property name="conferenceRoom2">
        	<ref local="conference2" />
        </property>
    </bean>
</beans>

Dependency Injection Pattern in Java using Spring (Part 2)

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.app</groupId>
    <artifactId>my-module</artifactId>
    <version>1</version>
 
    <dependencies>
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <defaultGoal>compile</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.5.1</version>
                <executions>
                    <execution>
                        <id>copy1</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>.\lib</outputDirectory>
                            <!-- other configurations here -->
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

IPerson.java

package work;

public interface IPerson {
    String getName();
}

Person.java

package work;

public class Person implements IPerson{

    String name = "default";

    public Person(String name)
    {
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }
}

Work.java

package work;

public class Work {
    IPerson office1;
    IPerson office2;

    public IPerson getOffice1() {
        return office1;
    }

    public void setOffice1(IPerson office1) {
        this.office1 = office1;
    }

    public IPerson getOffice2() {
        return office2;
    }

    public void setOffice2(IPerson office2) {
        this.office2 = office2;
    }
}

Main.java

package work;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        try(ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml")) {
	        Work work = (Work)context.getBean("Work");
	        System.out.println(work.getOffice1().getName() + " is at office 1");
	        System.out.println(work.getOffice2().getName() + " is at office 2");
        }
    }
}

bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="John" class="work.Person">
        <constructor-arg>
            <value>John</value>
        </constructor-arg>
    </bean>

    <bean id="Catherine" class="work.Person">
        <constructor-arg>
            <value>Catherine</value>
        </constructor-arg>
    </bean>

    <bean id="Work" class="work.Work">
        <property name="office1">
            <ref local="John"/>
        </property>
        <property name="office2">
            <ref local="Catherine"/>
        </property>
    </bean>
</beans>

Dependency Injection Pattern in C# using Unity (part 4)

Program.cs

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace validator
{
    interface IValidator<T>
    {
        bool isValid(T instance);
    }

    class IntegerOnlyValidator : IValidator<string>
    {
        public bool isValid(string instance)
        {
            int i = 0;
            return Int32.TryParse(instance, out i);
        }
    }

    class IntegerOnlyValidatorTest
    {
        [Dependency("validator")]
        public IValidator<string> validator { get; set; }
    }

    class GreaterThanFourValidator : IValidator<int>
    {
        public bool isValid(int instance)
        {
            return instance > 4;
        }
    }

    class GreaterThanFourValidatorTest
    {
        [Dependency("validator")]
        public IValidator<int> validator { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType<IValidator<string>, IntegerOnlyValidator>("validator");
                IntegerOnlyValidatorTest intOnly = container.Resolve<IntegerOnlyValidatorTest>();
                Console.WriteLine(intOnly.validator.isValid("5554"));
                Console.WriteLine(intOnly.validator.isValid("123ab"));
                
                container.RegisterType<IValidator<int>, GreaterThanFourValidator>("validator");
                GreaterThanFourValidatorTest greater4Only = container.Resolve<GreaterThanFourValidatorTest>();
                Console.WriteLine(greater4Only.validator.isValid(10));
                Console.WriteLine(greater4Only.validator.isValid(1));
            }
        }
    }
}

Dependency Injection via config file
Note: Add reference “System.Configuration”
App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <assembly name="validator"/>
    <namespace name="validator"/>

    <container>
      <register name="integeronly" type="IValidator[string]" mapTo="IntegerOnlyValidator" />
      <register name="greaterthan4" type="IValidator[int]" mapTo="GreaterThanFourValidator" />
      <register type="IntegerOnlyValidatorTest">
        <property name="validator">
          <dependency name="integeronly" />
        </property>
      </register>
      <register type="GreaterThanFourValidatorTest">
        <property name="validator">
          <dependency name="greaterthan4" />
        </property>
      </register>
    </container>
  </unity>
</configuration>

Program.cs

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace validator
{
    interface IValidator<T>
    {
        bool isValid(T instance);
    }

    class IntegerOnlyValidator : IValidator<string>
    {
        public bool isValid(string instance)
        {
            int i = 0;
            return Int32.TryParse(instance, out i);
        }
    }

    class IntegerOnlyValidatorTest
    {
        [Dependency("validator")]
        public IValidator<string> validator { get; set; }
    }

    class GreaterThanFourValidator : IValidator<int>
    {
        public bool isValid(int instance)
        {
            return instance > 4;
        }
    }

    class GreaterThanFourValidatorTest
    {
        [Dependency("validator")]
        public IValidator<int> validator { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();

                IntegerOnlyValidatorTest intOnly = container.Resolve<IntegerOnlyValidatorTest>();
                Console.WriteLine(intOnly.validator.isValid("5554"));
                Console.WriteLine(intOnly.validator.isValid("123ab"));

                GreaterThanFourValidatorTest greater4Only = container.Resolve<GreaterThanFourValidatorTest>();
                Console.WriteLine(greater4Only.validator.isValid(10));
                Console.WriteLine(greater4Only.validator.isValid(1));
            }
        }
    }
}

Dependency Injection Pattern in C# using Unity (part 3)

Program.cs

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace work
{
    interface IPerson
    {
        string Name { get; }
    }

    class Person : IPerson
    {
        [InjectionConstructor]
        public Person(string name)
        {
            this.name = name;
        }

        string name = "default";
        public string Name
        {
            get
            {
                return name;
            }
        }
    }

    interface IConferenceRoom
    {
        IPerson[] People { get; }
    }

    class ConferenceRoom : IConferenceRoom
    {
        IPerson[] people;
        public ConferenceRoom(IPerson[] people)
        {
            this.people = people;
        }

        public IPerson[] People
        {
            get
            {
                return people;
            }
        }
    }

    class Work
    {
        [Dependency("conferenceRoom1")]
        public IConferenceRoom conferenceRoom1 { get; set; }
        [Dependency("conferenceRoom2")]
        public IConferenceRoom conferenceRoom2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType<IPerson, Person>("John", new InjectionConstructor("John"));
                container.RegisterType<IPerson, Person>("Catherine", new InjectionConstructor("Catherine"));
                container.RegisterType<IConferenceRoom, ConferenceRoom>("conferenceRoom1",
                    new InjectionConstructor(new ResolvedArrayParameter<IPerson>(
                        new ResolvedParameter<IPerson>("John"),
                        new ResolvedParameter<IPerson>("Catherine"))));

                container.RegisterType<IPerson, Person>("Ben", new InjectionConstructor("Ben"));
                container.RegisterType<IPerson, Person>("Elizabeth", new InjectionConstructor("Elizabeth"));
                container.RegisterType<IConferenceRoom, ConferenceRoom>("conferenceRoom2",
                    new InjectionConstructor(new ResolvedArrayParameter<IPerson>(
                        new ResolvedParameter<IPerson>("Ben"),
                        new ResolvedParameter<IPerson>("Elizabeth"))));

                Work w = container.Resolve<Work>();

                Console.WriteLine("People at conference room 1");
                foreach (IPerson p in w.conferenceRoom1.People)
                {
                    Console.WriteLine(p.Name);
                }

                Console.WriteLine();

                Console.WriteLine("People at conference room 2");
                foreach (IPerson p in w.conferenceRoom2.People)
                {
                    Console.WriteLine(p.Name);
                }

                container.RegisterType<IPerson, Person>("Jennifer", new InjectionConstructor("Jennifer"));
                container.RegisterType<IPerson, Person>("Michael", new InjectionConstructor("Michael"));

                container.RegisterType<IConferenceRoom, ConferenceRoom>("conferenceRoom_OutofTheBlue",
                    new InjectionConstructor(new ResolvedArrayParameter<IPerson>(
                        new ResolvedParameter<IPerson>("Jennifer"),
                        new ResolvedParameter<IPerson>("Michael"))));
                w = container.Resolve<Work>(
                        new PropertyOverride("conferenceRoom2", new ResolvedParameter<IConferenceRoom>("conferenceRoom_OutofTheBlue")));

                Console.WriteLine();

                Console.WriteLine("People at conference room 1");
                foreach (IPerson p in w.conferenceRoom1.People)
                {
                    Console.WriteLine(p.Name);
                }

                Console.WriteLine();

                Console.WriteLine("People at conference room 2");
                foreach (IPerson p in w.conferenceRoom2.People)
                {
                    Console.WriteLine(p.Name);
                }
            }
        }
    }
}

Dependency Injection via config file
App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <assembly name="work"/>
    <namespace name="work"/>

    <container>
      <register name="John" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="John" />
        </constructor>
      </register>
      <register name="Catherine" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="Catherine" />
        </constructor>
      </register>
      <register name="Ben" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="Ben" />
        </constructor>
      </register>
      <register name="Elizabeth" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="Elizabeth" />
        </constructor>
      </register>
      <register name="Jennifer" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="Jennifer" />
        </constructor>
      </register>
      <register name="Michael" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="Michael" />
        </constructor>
      </register>
      <register name="conferenceRoom1" type="IConferenceRoom" mapTo="ConferenceRoom">
        <constructor>
          <param name="peopleArg">
            <array>
              <dependency name="John"/>
              <dependency name="Catherine"/>
            </array>
          </param>
        </constructor>
      </register>
      <register name="conferenceRoom2" type="IConferenceRoom" mapTo="ConferenceRoom">
        <constructor>
          <param name="peopleArg">
            <array>
              <dependency name="Ben"/>
              <dependency name="Elizabeth"/>
            </array>
          </param>
        </constructor>
      </register>
      <register name="conferenceRoom_OutofTheBlue" type="IConferenceRoom" mapTo="ConferenceRoom">
        <constructor>
          <param name="peopleArg">
            <array>
              <dependency name="Jennifer"/>
              <dependency name="Michael"/>
            </array>
          </param>
        </constructor>
      </register>
      <register type="Work">
        <property name="conferenceRoom1">
          <dependency name="conferenceRoom1" />
        </property>
        <property name="conferenceRoom2">
          <dependency name="conferenceRoom2" />
        </property>
      </register>
    </container>
  </unity>
</configuration>

Program.cs

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace work
{
    interface IPerson
    {
        string Name { get; }
    }

    class Person : IPerson
    {
        [InjectionConstructor]
        public Person(string name)
        {
            this.name = name;
        }

        string name = "default";
        public string Name
        {
            get
            {
                return name;
            }
        }
    }

    interface IConferenceRoom
    {
        IPerson[] People { get; }
    }

    class ConferenceRoom : IConferenceRoom
    {
        IPerson[] people;
        public ConferenceRoom(IPerson[] peopleArg)
        {
            this.people = peopleArg;
        }

        public IPerson[] People
        {
            get
            {
                return people;
            }
        }
    }

    class Work
    {
        [Dependency("conferenceRoom1")]
        public IConferenceRoom conferenceRoom1 { get; set; }
        [Dependency("conferenceRoom2")]
        public IConferenceRoom conferenceRoom2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();
                Work w = container.Resolve();

                Console.WriteLine("People at conference room 1");
                foreach (IPerson p in w.conferenceRoom1.People)
                {
                    Console.WriteLine(p.Name);
                }

                Console.WriteLine();

                Console.WriteLine("People at conference room 2");
                foreach (IPerson p in w.conferenceRoom2.People)
                {
                    Console.WriteLine(p.Name);
                }

                w = container.Resolve(new PropertyOverride("conferenceRoom2", 
                    new ResolvedParameter("conferenceRoom_OutofTheBlue")));

                Console.WriteLine();

                Console.WriteLine("People at conference room 1");
                foreach (IPerson p in w.conferenceRoom1.People)
                {
                    Console.WriteLine(p.Name);
                }

                Console.WriteLine();

                Console.WriteLine("People at conference room 2");
                foreach (IPerson p in w.conferenceRoom2.People)
                {
                    Console.WriteLine(p.Name);
                }
            }
        }
    }
}

Dependency Injection Pattern in C# using Unity (part 2)

Note: Use NuGet to install Unity

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace work
{
    interface IPerson
    {
        string Name { get; }
    }

    class Person : IPerson
    {
        [InjectionConstructor]
        public Person(string name)
        {
            this.name = name;
        }

        string name = "default";
        public string Name
        {
            get
            {
                return name;
            }
        }
    }

    class Work
    {
        [Dependency("office1")]
        public IPerson office1 { get; set; }
        [Dependency("office2")]
        public IPerson office2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType<IPerson, Person>("office1", new InjectionConstructor("John"));
                container.RegisterType<IPerson, Person>("office2", new InjectionConstructor("Catherine"));
                Work w = container.Resolve<Work>();

                Console.WriteLine(w.office1.Name + " is at office 1");
                Console.WriteLine(w.office2.Name + " is at office 2");
            }
        }
    }
}

Dependency Injection via config file
Note: Add reference “System.Configuration”
App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <assembly name="work"/>
    <namespace name="work"/>

    <container>
      <register name="John" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="John" />
        </constructor>
      </register>
      <register name="Catherine" type="IPerson" mapTo="Person">
        <constructor>
          <param name="name" value="Catherine" />
        </constructor>
      </register>
      <register type="Work">
        <property name="office1">
          <dependency name="John" />
        </property>
        <property name="office2">
          <dependency name="Catherine" />
        </property>
      </register>
    </container>
  </unity>
</configuration>

Program.cs

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace work
{
    interface IPerson
    {
        string Name { get; }
    }

    class Person : IPerson
    {
        [InjectionConstructor]
        public Person(string name)
        {
            this.name = name;
        }

        string name = "default";
        public string Name
        {
            get
            {
                return name;
            }
        }
    }

    class Work
    {
        [Dependency("office1")]
        public IPerson office1 { get; set; }

        [Dependency("office2")]
        public IPerson office2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();

                Work w = container.Resolve<Work>();

                Console.WriteLine(w.office1.Name + " is at office 1");
                Console.WriteLine(w.office2.Name + " is at office 2");
            }
        }
    }
}

Dependency Injection Pattern in C# using Unity

Note: Use NuGet to install Unity

IExam.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace school
{
    interface IExam
    {
        string GetQuestions();
    }
}

EnglishExam.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace school
{
    class EnglishExam : IExam
    {
        public string GetQuestions()
        {
            return "English Questions";
        }
    }
}

MathExam.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace school
{
    class MathExam : IExam
    {
        public string GetQuestions()
        {
            return "Math Questions";
        }
    }
}

ExamService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace school
{
    class ExamService
    {
        IExam exam = null;
        public ExamService(IExam exam)
        {
            this.exam = exam;
            Console.WriteLine(exam.GetQuestions());
        }

        public string GetQuestions()
        {
            return exam.GetQuestions();
        }
    }
}

Program.cs

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace school
{
    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType<IExam, EnglishExam>();
                //container.RegisterType<IExam, MathExam>();

                ExamService exam = container.Resolve<ExamService>();

                exam.GetQuestions();
            }
        }
    }
}

Dependency Injection via configuration file
Note: Add reference “System.Configuration”

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <assembly name="school"/>
    <namespace name="school"/>
    
    <container>
      <register type="IExam" mapTo="EnglishExam" />
      <!--<register type="IExam" mapTo="MathExam" />-->
    </container>
  </unity>
</configuration>

Program.cs

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace school
{
    class Program
    {
        static void Main(string[] args)
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.LoadConfiguration();

                ExamService exam = container.Resolve<ExamService>();
                exam.GetQuestions();
            }
        }
    }
}

Dependency Injection Pattern in Java using Spring

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.app</groupId>
    <artifactId>my-module</artifactId>
    <version>1</version>
 
    <dependencies>
		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <defaultGoal>compile</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.5.1</version>
                <executions>
                    <execution>
                        <id>copy1</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>.\lib</outputDirectory>
                            <!-- other configurations here -->
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

IExams.java

package exam;

public interface IExams {
	String generateExam();
}

EnglishExam.java

package exam;

public class EnglishExam implements IExams {

	String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String generateExam() {
		return name + ", English Exam Generated";
	}

}

MathExams.java

package exam;

public class MathExams implements IExams {
	String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String generateExam() {
		return name + ", Math Exam Generated";
	}

}

ExamService.java

package exam;

public class ExamService {
	IExams exam;

	public IExams getExam() {
		return exam;
	}

	public void setExam(IExams exam) {
		this.exam = exam;
	}
	
	public String generateExam()
	{
		return exam.generateExam();
	}
}

Exams.java

package exam;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Exams {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
		ExamService exams = (ExamService) context.getBean("ExamService");
		String exam = exams.generateExam();
		System.out.println(exam);
		context.close();
	}
}

bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
   
    <bean id="EnglishExam" class="exam.EnglishExam">
        <property name="Name" value="john"></property>
    </bean>
    
    <bean id="MathExams" class="exam.MathExams">
        <property name="Name" value="steve"></property>
    </bean>
    <bean id="ExamService" class="exam.ExamService">
        <property name="Exam">
            <!-- <ref local="MathExams"/> -->
            <ref local="EnglishExam"/>
        </property>
    </bean>       
</beans>

Dependency Injection Pattern in C#

1) Create a project called “Exam”
2) Add a new project with type “Class Library” and name “IExam”
IExam.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public interface IExam
{
    string generateExam(string name);
}

3) Add a new project with type “Class Library” and name “EnglishExam”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class EnglishExam : IExam
{
    public string generateExam(string name)
    {
        return name + ", English Exam Generated";
    }
}

4) Add a new project with type “Class Library” and name “MathExam”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class MathExam : IExam
{
    public string generateExam(string name)
    {
        return name + ", Math Exam Generated";
    }
}

5) Add “Application Configuration File” in Exam project

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="examClass" value="MathExam"/>
    <add key="param1" value="John"/>
  </appSettings>
</configuration>

6) Modify the Program.cs in Exam project

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Configuration;

class Program
{
    static void Main(string[] args)
    {
        string examClass = ConfigurationManager.AppSettings["examClass"];
        string param1 = ConfigurationManager.AppSettings["param1"];

        Assembly SampleAssembly = Assembly.LoadFrom(examClass + ".dll");
        IExam o = (IExam)SampleAssembly.CreateInstance(examClass);
        string exam = o.generateExam(param1);
        Console.WriteLine(exam);
    }
}