Friday, June 15, 2012

Unity Container

Unity Application Block is a dependency injection container which supports for,
  • Property Injection
  • Constructor Injection
  • Method Call Injection
Dependency injection is a design pattern which allows to injects the components at run time, rather than the compile time.

Property Injection

Below sample project is, the way to bind different database implementation(Oracle & SQL implementation) at run time, without compile the application again and again.

Create a solution and add projects as follow.

In the UnitLib project, declare the interfaces which we are going to bind objects at run time. It's better to define the interfaces in a separate project. Because dependency injection is pattern is about loose coupling and separation of behavior.
Implement the interfaces in the UnityLibImplOracle and UnityLibImplSQL projects. We should write the different implementation in separate projects. According to the sample, it's better to separate the Oracle implementation and the SQL implementation.
In the facade we can define the StudentFacade like below.
The real implementation of IUnityStudent's Register method will not be known till the run time.
In the run-time the concrete implementation of the IUnityStudent will be injected  by Unity, depending on it's configuration. In the type we should define the class of the property with the name space and then by separating comma, we should define the Dll file name. In mapTo xml tag define the concrete class that should be use in the run time.

The entry point for the application is like,
In the above configuration file, in the run-time the program will access the Oracle based implementation. By changing only the configuration file, in the run time we can load the implementation of the SQL.

In the above code we are calling the resolve no argument method. But we can pass the registration name and through that we can bind the related objects at the run time.

Constructor Injection

Create a class called Student
In the constructor after the object initialization, using setters, the FirstName will be set.

Method Injection

In the UserFacade class define the method that we need to inject at the run time.
We can configure the App.config file like below.
According to the Microsoft, If you are not sure which type of injection to use, the recommendation is that you use constructor injection. This is likely to satisfy almost all general requirements.

No comments:

Post a Comment