Wednesday, December 30, 2009

Unity Application Block – Complete series


The links for the unity application block tutorials from my site.

Unity Application Block – Creating an Handler for exception application block


As mentioned in my previous post, Unity can be used to address cross cutting concerns by registering and invoking interceptors. In this post, I’ll show how to create an Exception handler for the enterprise library exception block using unity to reduce the cross concerns in your code for exception handling.
Step 1: Create ICallHanlder implementation
public class ExceptionCallHandler : ICallHandler
{
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        var __Result = getNext()(input, getNext);
        if (__Result.Exception == null)
            return __Result;
        var __Rethrow = ExceptionPolicy.HandleException(__Result.Exception, "MyExceptionPolicy");
        if (__Rethrow) throw __Result.Exception;
        else throw new ArgumentException("An exception occured");
    }

    public int Order { get; set; }
}
Step 2: Create an attribute for Exception Handling
public class ExceptionCallHandlerAttribute : HandlerAttribute
{
    public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
    {
        return new ExceptionCallHandler();
    }

Step 3: Use the handler attribute in your code.
[ExceptionCallHandler]
void Update(T instance);
Step 4: Configure the container
IUnityContainer ___Container = new UnityContainer();
___Container.AddNewExtension<Interception>();
___Container.RegisterType<IRepository<Employee, Guid>, EmployeeRepository>();
___Container.Configure<Interception>().SetDefaultInterceptorFor<IRepository<Employee, Guid>>(new TransparentProxyInterceptor());

It’s that simple to remove the try catch blocks from your code!!!

Unity Application Block – Interceptor pattern


An interceptor pattern is a software design pattern that is used when software systems or frameworks want to offer a way to change, or augment, their usual processing cycle. Key aspects of the pattern are that the change is transparent and used automatically. In essence, the rest of the systems does not have to know something has been added or changed and can keep working as before. To facilitate this, a predefined interface for extension has to be implemented, some kind of dispatching mechanism is required where interceptors are registered (this may be dynamic, at runtime, or static, e.g. through configuration files) and context objects are provided, which allow access to the frameworks internal state.
The interceptor design pattern can be used for addressing issues like cross-cutting concerns, issues that cut across the entire software. Many of the cross cutting concerns happen only at either the start or the end of a method. You log when a method is called. You check your inputs for validity before processing. You handle exceptions after the method fails. This leads to a different approach to implementing cross-cutting concerns. You can put some special handling before or after method calls to handle the cross-cutting concerns, get the code out of the methods, and enhance its maintainability. Unity provides support for interception through the Interception container extension.
The interception mechanism is based around three basic concepts: matching rules, call handlers, and interceptors. Matching rules are simple but flexible objects that determine which methods should have extra handling applied. Call handlers are objects that actually implement the cross-cutting concerns. They can run before or after the method. They can modify method parameters or return values. They can even stop the method from being called at all or call it multiple times. The matching rules and call handlers are grouped together into interception policies. The interception policy uses the matching rules to define which methods get intercepted and uses the call handlers to define what processing to perform on the intercepted object.
For e:g we can implement a logic for every method to check whether the parameters passed to the method are validated against null reference. My first task is to implement a call handler for this cross cutting concern. Unity provides an Interface ICallHandler to define call handlers in your code.
public class ParameterInfoNotNullHandler : ICallHandler
{
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        for (int i = 0; i < input.Inputs.Count; i++)
        {
            object target = input.Inputs[i];
            if (target == null)
            {
                ParameterInfo parameterInfo = input.Inputs.GetParameterInfo(i);
                ArgumentNullException ex = new ArgumentNullException(parameterInfo.Name);
                return input.CreateExceptionMethodReturn(ex);
            }
        }

        return getNext()(input, getNext);
    }

    public int Order { get; set; }
}
Now for defining an attribute to be used for injecting the logic I define a ParameterInfoNotNullAttribute
public class ParameterInfoNotNullAttribute : HandlerAttribute
{
    public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
    {
        return new ParameterInfoNotNullHandler();
    }
}
And when I define my interface with the methods
public interface IRepository
{
-    - Other methods
    [ParameterInfoNotNull(Order = 1)]
    T GetById(Id id); 
}
The class that implements the interface does not need to worry about the null validation
public Employee GetById(Guid id)
{
    return ___EmployeeCollection.First<Employee>(x => x.Id == id);
}
The only thing left is to configure the container.
IUnityContainer ___Container = new UnityContainer();
___Container.AddNewExtension<Interception>();
___Container.RegisterType<IRepository<Employee, Guid>, EmployeeRepository>();
___Container.Configure<Interception>().SetDefaultInterceptorFor<IRepository<Employee, Guid>>(new TransparentProxyInterceptor());

Unity Application Block – Configuring containers at Run Time


Unity application block also allows you to configure the container and perform injection at run time by directly creating and populating instances of the configuration classes. This provides an alternative approach to using attributes within the target classes or configuring injection requirements using the configuration file.
The RegisterType method allows you to specify the type to be registered in the container and later retrieve it using the Resolve method.
___Container = new UnityContainer()
                .RegisterType<IRepository<Employee, Guid>, EmployeeRepository>();
var __Repository = ___Container.Resolve<IRepository<Employee, Guid>>();
You can also specify the injection constructor for a class either via the InjectionConstructor attribute of through the RegisterType overload that allow configuration injection by accepting InjectionMembers. The constructor defined as InjectionConstructor will be used as the default on while resolving the type.
[InjectionConstructor]
public EmployeeViewModel(IRepository<Employee, Guid> repository)
{
    Repository = repository;
}
[TestInitialize]
public void Initialize()
{
    ___Container = new UnityContainer()
        .RegisterType<IRepository<Employee, Guid>, EmployeeRepository>();           
}

[TestMethod]
public void InjectionConstructor_test()
{
    var __ViewModel = ___Container.Resolve<EmployeeViewModel>();
    Assert.IsNotNull(__ViewModel, "Failed to retrieve ViewModel");
    Assert.IsNotNull(__ViewModel.Repository, "Failed to retrieve Repository");
}

Thursday, December 24, 2009

Unity Application Block – Loading configuration information


The Unity Application Block does not automatically read the configuration information or create and prepare containers. You must programmatically instantiate a Unity container in your application. You can programmatically configure it with registrations, type mappings, and any extensions or you can configure it by reading configuration information from a file.
The following example code demonstrates how to configure unity container and load the instances from the configuration information.
public interface IRepository
{
    void Insert(T instance);
    void Update(T instance);
    T GetById(Id id);
    IEnumerable GetAll();
    bool Delete(Id id);
}
The IRepository interface is defined in the assembly UnitySamples.Infrastructure. The implementation is defined in the assembly UnitySamples.DataAccessLayer in the class EmployeeRepository
public class EmployeeRepository : IRepository<Employee, Guid>
{
    public EmployeeRepository()
    {
        ___EmployeeCollection = EmployeeFactory.Create();
    }

    public void Insert(Employee instance)
    {
        ___EmployeeCollection.ToList().Add(instance);
    }

    public void Update(Employee instance)
    {
        var __Employee = GetById(instance.Id);
        if (__Employee == null) return;
        __Employee.FirstName = instance.FirstName;
        __Employee.LastName = instance.LastName;
    }

    public Employee GetById(Guid id)
    {
        return ___EmployeeCollection.First<Employee>(x => x.Id == id);
    }

    public IEnumerable<Employee> GetAll()
    {
        return ___EmployeeCollection;
    }

    public bool Delete(Guid id)
    {
        var __Count = ___EmployeeCollection.ToList().RemoveAll(x => x.Id == id);
        return __Count > 0;
    }

    static IEnumerable<Employee> ___EmployeeCollection;
}
My application configuration file looks like
<configuration>
  <configSections>
    <section name="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
                   Microsoft.Practices.Unity.Configuration,
                   Version=1.2.0.0,
                   Culture=neutral,
                   PublicKeyToken=31bf3856ad364e35" />
  configSections>
  <unity>
    <typeAliases>
     
      <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
     
      <typeAlias alias="IRepository`2" type="UnitySamples.Infrastructure.Interfaces.IRepository`2, UnitySamples.Infrastructure" />
      <typeAlias alias="employeeRepository" type="UnitySamples.DataAccessLayer.EmployeeRepository, UnitySamples.DataAccessLayer" />
    typeAliases>
    <containers>
      <container name="unityContainer">
        <types>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
          <type type="IRepository`2"
                mapTo="employeeRepository"
                name="EmployeeRepository">
            <lifetime type="singleton" />
          type>
        types>       
      container>
    containers>
  unity>
configuration>
As you can see I have mentioned the IRepository interface preceeding with a ‘`’ and 2. The .NET Framework convention for expressing generic types is ObjectWithOneType`1, where the digit following the "`" matches the number of types contained in the generic type.
To load the configuration information, I have my code as
IUnityContainer __Container = new UnityContainer();
UnityConfigurationSection __Section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
Assert.IsNotNull(__Section, "Failed to load unity section from configuration");

__Section.Containers["unityContainer"].Configure(__Container);

var __EmployeeRepository = __Container.Resolve<IRepository<Employee, Guid>>("EmployeeRepository");
Assert.IsNotNull(__EmployeeRepository, "Failed to load the repository instance from the configuration file mapping");

var __EmployeeCollection = __EmployeeRepository.GetAll();
Assert.IsNotNull(__EmployeeCollection, "Repository failed to retrieve employee data");
Assert.IsTrue(__EmployeeCollection.Count() > 0, "Repository failed to retrieve employee data");
We’ll continue looking into the details of the Unity Application block in the upcoming posts. Till then happy programming!!!.

Unity Application Block – Understanding configuration file schema


The Unity Application Block can read configuration information from an XML configuration file. By default, this is the App.config or Web.config file for your application. However, you can load configuration information from any other XML format file or from other sources. In this post we’ll see the list of elements and attributes used to configure the Unity Application Block and how each section is used to meet your application requirements.
The configuration file that belongs to the application contains multiple configuration sections. E.g. Sections for data access configuration information, Exception handling and logging information, Application settings etc. The unity configuration information is defined in the unity configuration section, which will be specified under element of your application configuration file.
<configuration>
  <configSections>
    <section name="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
                   Microsoft.Practices.Unit.Configuration,
                   Version=1.2.0.0,
                   Culture=neutral,
                   PublicKeyToken=31bf3856ad364e35" />
  configSections>
configuration>
The section handler declaration above specifies the name of the unity configuration section as unity. You can use any name as your convention. The samples in this articles series will use the name as unity. As mentioned before the unity element specifies the application block configuration information. The unity element has the following child elements.
·         typeAliases
·         containers
typeAliases Element
This element holds a collection of aliases that you can use to specify the types required in mappings, instances etc. for unity containers. The typeAliases element contains the typeAlias child elements, which have alias and type attributes that can be referred to the type elsewhere in the configuration.
<unity>
  <typeAliases>  
    <typeAlias alias="myTypeAlias" type="MyNamespace.TypeName, MyAssembly" />
  typeAliases>
unity>
containers Element
This element holds details of an individual container. The container element has the following child elements.
·         types
·         instances
·         extensions
·         extensionConfig
<containers>
  <container name="containerOne">
    <types>
     
    types>
    <instances>
     
    instances>
    <extensions>
     
    extensions>
    <extensionConfig>
     
    extensionConfig>
  container>
containers>
types Element
This element holds a collection of the registered type mappings for the container. This element holds the type child element that defines a type mapping for the unity container.
<types>
  <type type="Blogsprajeesh.Blogspot.Infrastructure.IRepository"
        mapTo="BlogsPrajeesh.Blogspot.DataAccess.SQLRepository"
        name="Repository">
  type>
types>
You can also specify the lifetime manager for each mapping. The default value will be a transient lifetime manager which creates a new instance of the registered, mapped or requested type each time a call to resolve the type is made. You can specify a lifetime to be singleton, per thread or external.
<typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
<types>
  <type type="Blogsprajeesh.Blogspot.Infrastructure.IRepository"
        mapTo="BlogsPrajeesh.Blogspot.DataAccess.SQLRepository"
        name="Repository">
    <lifetime type="singleton" />
  type>
types>

The typeConfig element of the type child element specifies the general configuration for a type/ name configuration. You can use this element to specify or configure custom dependency injection settings for the container.
<types>
  <type type="Blogsprajeesh.Blogspot.Infrastructure.IRepository"
        mapTo="BlogsPrajeesh.Blogspot.DataAccess.SQLRepository"
        name="Repository">
    <lifetime type="singleton" />
    <typeConfig>
      <constructor>
        <param name="connectionString" parameterType="string">
          <value value="MyConnectionString" />
        param>
      constructor>
    typeConfig>
  type>
types>
instances Element
This element holds a collection of the existing object instances for the container.
<instances>
  <add name="MyConnectionString" type="System.String" value="connection string value" />
instances>
Next part of the series we’ll see how to load the configuration information setup in the config file into the container and working with that information.