Ivan Paniagua Monroy {Blog about BI, SQL, Azure & Microsoft.NET Technologies}

Entradas etiquetadas como ‘Unity’

Unity Application Block and MVC

 

Always, one of the most gratifying things that every developer always said, is finding a tool that permit simplify the work of everyday.  Save time and at the same time add quality to development of software.
Microsoft has a departament to Learn and Apply what is called Patterns & Practices in Software. Inside of that there is tool called “Application Blocks”.  that help us to simplify the work of development, that tell us how to build the software instead of must be do it.
There are a lot of Blocks to specific task for example to access to data base, logging best practices, caching, etc.
 
In this paper I going to explore one of them,  a little confusing and less know, Its Unity Block and Inversion of Control (IoC)  and Dependency Injection (DI) patterns and explain how to use it together with MVC – Model View Controller pattern. (The explanation of MVC its outside of scope).One of them As application size and complexity increase it becomes more and more difficult to reuse existing components and integrating these components to form an interconnected architecture because of the dependencies of the components. One way to reduce dependencies is by using Dependency Injection, which allows you to inject objects into a class, rather than relying on the class to create the object itself.

Inversion of Control it helps towars a loosely coupled arquitecture. DI is one way in which IoC can be applied. There are another IoC called “Service Locator” but as Martin Fowler thinks the “choice between them is less important than the principle of separating configuartion from use”. Besides
the pattern “Service Locator” is a better choice when you are buildind a single application, while Dependency Injection can be more appropiate otherwise.

Consider a scenario where we have a customer class which needs to perform get data (getPerson) operation on database. The customer class should be customizable to get data in either Sql server or oracle database. In future we should also be able to add new databases with out disturbing the customer class.

Define two classes one for SQL server and other for Oracle. But because the object creational activity needs to be done by the Controller class (could be better in Model but just to remain simple) it still needs to be aware of the concrete classes.

I will use a bit of code on the MVC to help illustrate the basic problem that we intented to solve:

public classPersonController : Controller
{

public ActionResult Details()

{

clsOracleServer server = new clsOracleServer();

var p = server.GetPerson();

return View(p);

}

}

If we want to use to access to SQL server we can do it like this:

public class PersonController : Controller
{

public ActionResult Details()

{

clsSqlServer server = new clsSqlServer();

var p = server.GetPerson();

return View(p);

}

}

The next thing comes in mind is creation patterns. If we can introduce a factory who takes the creational aspect of the concrete classes thus isolating the concrete classes.

Here are the issues with factory which makes us force to think about some other solutions:-

  • Everything is hardcoded: – The biggest issues with factory are it can not be reused across applications. All the options are hardcoded in the factory itself which makes the factory stringent to particular implementation.
  • Interface dependent: – The base on which factories stands are common interfaces. Interfaces decouple the implementation and the object creation procedure. But then all the classes should implement a common interface. This is a limitation by itself again.
  • Factories are custom: – They are very much custom to a particular implementation.
  • Everything is compile time: – All dependent objects for an object in factory have to be known at compile time.

I will not be explaining factory pattern becouse is out of scope.

Dependency Injection
Ok, I will show you a magic…Rather than writing those huge line of code for factory…lets go the DI way (Dependency injection).
Dependency Injection is moving from procedural approach to more object oriented style of applications development. The dependecny (data service) is injected into the calling function.

Defining common Interface
We  need a common interface to do that so we can change ahead to use SQL or Oracle Database.
So let the class references the interface and we should be able to inject the concrete type into the controller and then into view.

namespace MvcUnity.Models
{
interface iDatabase
{
   Person GetPerson();
}
}
Now we move the actual data access out of the Controller into a separate class that implement the iDatabase into particular type. For example  SQL Server.

namespace MvcUnity.Models
{
public class clsSqlServer : iDatabase
{
   public Person GetPerson()
   {
       var p = new Person
           {
               FirstName = “SQL”,
               LastName = “SERVER”
           };
       return p;
   }
}
}

the version of Oracle type is vey similar:

namespace MvcUnity.Models
{
public class clsOracleServer : iDatabase
{
   public Person GetPerson()
   {
       var p = new Person
           {
               FirstName = “ORACLE”,
               LastName = “SERVER”
           };
       return p;
   }
}
}

Providing the injection gateway

In the Database class we will reference the interface and expose the public property using [Dependency] attribute. This exposure is essential for the unity container. Unity container needs some kind of gateway by which it can inject the object. So what we have done is we have exposed the interface ‘iDatabase’ publicly.

namespace MvcUnity.Models
{
class clsDataBase
{
   [Dependency]
   public iDatabase Database { get; set; }
   public Person GetPerson()
   {
       return Database.GetPerson();
   }
}
}

Defining the config file

To achieve high customization unity application allows us to specify how the injection will work in the config files ( web.config and app.config ). As this example is a web application we will be defining an web.config file.

You can see below a simple template of Web.config file from unity perspective. The Configsection is compulsory and keep it as it is. The important section to be noted is the types section which comes under container section. In this we specify which interfaces map to which concrete class. The unity container creates object from this section and inserts in to the customer object through the dependency attribute.

<unity>
<containers>
 <container>
   <types>
     <!–<type type=”UnityBlock.iDatabase,UnityBlock” mapTo=”UnityBlock.clsSqlServer,UnityBlock” /> –>
     <type type=”MvcUnity.Models.iDatabase, MvcUnity”
           mapTo=”MvcUnity.Models.clsOracleServer, MvcUnity” />
   </types>
 </container>
</containers>
</unity>

Controller or Cliente Code
Injection can be done using containers. So basically you need to put both the classes in to the container and the container will create object and inject the same in to the other class

With this your controller class does not need to worry about creating objects and knowing the concrete objects.

Now that we know the benefit of containers we will explore unity application block which helps us to achieve dependency injection inside of the controller.

public ActionResult Details(int id)
   {
       IUnityContainer container = new UnityContainer();
       UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection(“unity”);
       section.Configure(container);
       clsDataBase objcutomer = container.Resolve<clsDataBase>();
       var p = objcutomer.GetPerson();
       return View(p);
   }

The client code is pretty simple. The first step us we create the unity container object. In the second step we read the unity section. In step 3 we configure the container using the unity section data.