Injecting property dependencies

by Jacobus Meintjes January 24, 2010 20:48

First you will have to create the class with the properties that need to be injected.

   1:      public class Person
   2:      {
   3:          private int ival;
   4:         
   5:          //Dependency attribute is required for Unity to know that this is the property to
   6:          //inject with the registered object.
   7:          [Dependency]
   8:          public int IVal
   9:          {
  10:              get { return ival; }
  11:              set { ival = value; }
  12:          }
  13:   
  14:          public override string ToString()
  15:          {
  16:              return IVal.ToString();
  17:          }
  18:       }

Then create the Unity container that will be configured to inject the dependency.

   1:  IUnityContainer unityContainer = new UnityContainer();                        

You will now need to configure the UnityContainer to register the object required by the Person class.

   1:  //Person - class to assign the injected member to
   2:  //IVal - member name of class Person
   3:  //10 - Value to be assigned to IVal
   4:  unityContainer.Configure<InjectedMembers>()
   5:                      .ConfigureInjectionFor<Person>(new InjectionProperty("IVal", 10));

Doing this and using the Person class won't automatically assign the value to the member e.g.

   1:  Person p = new Person();
   2:   
   3:  //This will output 0 (zero) as IVal is unassigned, causing the default for int to be displayed.
   4:  Console.WriteLine("Value of IVal is {0}", p.ToString());

To allow for the property to be resolved, you will have to resolve the object using Unity's resolve method.

   1:  Person p = unityContainer.Resolve<Person>(); //Create Person and assign a value to IVal.
   2:   
   3:  //This will give a value of 10 as the property is assigned correctly.
   4:  Console.WriteLine("Value of IVal is {0}", p.ToString());

Getting property injections working correctly, took a while as I had to start using Factory classes to create and initialize classes required for my domain. Using factory classes allowed me to use Unity within my unit tests to register mocked objects.

Tags: , ,

C# | Dependency Injection | Unity

Configuring Unity for the Todo application

by Jacobus Meintjes December 18, 2009 10:33

 

Working on a small Todo MVC application, I had to start using Unity for dependency injection. As I worked with Unity, I learned how to configure it to let me inject into a constructor, property and method call.

 

Configuration starts off with the web.config, adding a new section to allow for Unity to be configured.

web.config

<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" requirePermission="false"/>

Registering the new section will allow you to set the path to the Unity configuration file.

<unity configSource="unity.config"/>

After doing this you can start with the configuration of Unity.

 

unity.config

 

<?xml version="1.0"?>

  <unity>

    <typeAliases>

      <typeAlias alias="string" type="System.String, mscorlib" />

      <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />

     

      <typeAlias alias="ITodoRepository" type="Todo.Repository.Contracts.ITodoRepository, Todo.Repository.Contracts" />    

 

      <!-- To swop out dependancies, you swop the two Repositories below-->

      <typeAlias alias="TodoRepository" type="Todo.Repository.Sql.TodoRepository, Todo.Repository.Sql" />

      <!--<typeAlias alias="TodoRepository" type="Todo.Repository.Fake.TodoRepository, Todo.Repository.Fake" />-->

 

      <typeAlias alias="ITodoService" type="Todo.Services.Contracts.ITodoService, Todo.Services.Contracts" />

      <typeAlias alias="TodoService" type="Todo.Services.TodoService, Todo.Services" />

    </typeAliases>

 

    <containers>

      <container>

        <types>

          <type type="ITodoRepository" mapTo="TodoRepository" >

            <lifetime type="singleton" />

            <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">

              <constructor>

                <param name="connectionString" parameterType="string">

                  <value value="data source=.\SQLExpress;integrated security=sspi; database=todo"/>

                </param>

              </constructor>

            </typeConfig>

          </type>

          <type type="ITodoService" mapTo="TodoService" >

            <lifetime type="singleton" />

            <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">

            </typeConfig>

          </type>;

        </types>

      </container>

    </containers>

  </unity>

 

Important sections in the xml config file:

 

1.       Register the interface to use:

<typeAlias alias="ITodoService" type="Todo.Services.Contracts.ITodoService, Todo.Services.Contracts" />

 

2.       Register the class that implements the interface:

<typeAlias alias="TodoService" type="Todo.Services.TodoService, Todo.Services" />

 

3.       Mapping the interface to the implementation:

<type type="ITodoService" mapTo="TodoService" >

 

Example - Constructor injection

private ITodoService todoService;

public TodoController(ITodoService service)

{

     todoService = service;

}

Example - Property injection

[Dependency]

public ITodoService TodoService

{

     get;

     set;

}

 

This is accomplished using the Dependency attribute with the property.

 

Example – Method injection

private ITodoService todoService;

 

[InjectionMethod]

public void SetTodoController(ITodoService service)

{

     todoService = service;

}

 

This is accomplished using the InjectionMethod attribute with the method.

 

Note: The project that you want to use with Unity must compile into the web application’s bin folder.

 

Demonstrating DI

The best section to display the use of DI is the repository section in the config file:

1.       Register the interface to use: [Stays the same]

<typeAlias alias="ITodoRepository" type="Todo.Repository.Contracts.ITodoRepository, Todo.Repository.Contracts" />    

 

2.       Register the class that implements the interface:

<typeAlias alias="TodoRepository" type="Todo.Repository.Sql.TodoRepository, Todo.Repository.Sql" />

 

3.       Mapping the interface to the implementation:

<type type="ITodoRepository" mapTo="TodoRepository">

 

4.       Swopping the original implementation with a different one:

<typeAlias alias="TodoRepository" type="Todo.Repository.Fake.TodoRepository, Todo.Repository.Fake" />

 

The only difference to note, is when you implement a different type: type="Todo.Repository.Fake.TodoRepository, Todo.Repository.Fake" Only changing the namespace and the assembly allows you to use a completely different implementation of the interface. There will also be no need to recompile you're site.

Tags:

C# | Dependency Injection

Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen | Modified by Mooglegiant

About Me

Jacobus Meintjes
 
C# developer working with ASP.Net and/or Windows Forms.
Email Me

Cumulus

This will be shown to users with no Flash or Javascript.

Widget Twitter not found.

Root element is missing.X