Dependency Injection using Microsoft Unity Application block ( DI IOC) – 30 minutes training

Dependency Injection using Microsoft Unity Application block ( DI IOC) – 30 minutes training

In this video we will try to understand what exactly is this word Dependency Injection and how can we implement Dependency Injection by using Unity Application Block. Now my honest suggestion is before you go and watch this video of Dependancy Injection Please go and first watch the video of Inversion of control so its like pre requisite for this video. Because the main concept is Inversion of Control and Dependency Injection is one of the techniques to implement Inversion of Control So first go and watch the video of Inversion of Control and then you can continue with this Dependency Injection video So what i’ll do here is I am going to go and start with a very very small sample 3 layer Architecture Project Sample code actually not exactly a full blown application I will talk about the problems what is related to that 3 layer Architecture and how we can go and solve those issues by using Dependency Injection So let me just start with a very simple definition first of Dependency Injection Then I will go ahead with coding the simple sample application. Dependency Injection is a technique which helps you to inject dependent objects of a class. means for example you have a class program here and in this class program is using some object like customer I don’t have a customer class at this moment but let say it is using a Customer Object like this The Dependency Injection framework will come and it will come and Inject this object inside your program class. Ok So again i am iterating Dependency Injection is a technique Which helps you to inject dependent object of a class That’s a very simple definition to start with But in order to understand you know what that sentences means Let me go ahead and create a very very simple 3 layer project here and then will talk about you know what this sentence means So normally when we say a 3 layer application A 3 layer application is divided in to 3 sections One is a user Interface the other one is a Business logic and the last one is the Data Access Layer Now what i will do is In order to keep this application or keep this sample code simple I have created a very simple Console application here Our console application will be the UI Then I will create a very simple Middle Layer here and a simple Data Access Layer I have not used a winform application or a WPF application ASP.NET Webform application because we will unnecessary get into button click events, Page load events and we will lose our focus of learning Dependency Injection To keep the focus to learn Dependency Injection I have just created my User Interface The very simple console application here I have a very simple console application and let say this console application actually talks to a Middle Layer or a business component called as customer object or a customer class I’ll say rather The Customer class internally calls to a Data Access Layer In professional application or Enterprise Application when you create this three layers you normally create a new class project In other words if you are creating a Middle Layer you will say View solution explorer and you will go and add a new project a clas project If you want to code a Data Access Layer again you will click on new add project and you will create a new physical project and you will put those respective classes in those projects At this moment in order to keep it simple so that we can see the whole code in one go I am going to code all those three layers inside this same namespace here customer UI I will not be creating new class projects but I am going to create all those classes inside this same namespace So that we can see the whole code in one go rather than switching between class project Our main intention is to learn dependency Injection and not three layer architecture I am going to create all of those three layers inside this namespace it self You can visualize something like this This class program is your User Interface Layer Let me add a Middle Layer here I am going to add a very simple Middle Layer here Lets say a customer class I’ll keep one property here at this moment Let say customer name property We are not going to code full blown customer class here Here is a customer class with customer name property This is my Middle Layer here It also has a Add method I am going to say here public void add When anybody creates any object of this class and he invokes this add method then he actually goes and invoke the Data Access Layer I have a User Interface I have a Middle Layer I have a UI Layer Lets go and code a simple Data Access Layer Let us assume that your customer class is calling up a SQL Server Data Access Layer Our back end is our SQL server We are not going to write any kind of SQL code We are not going to use Data set or data reader because our main concentration is dependency Injection Let say that you have nice SQL Server Data Access Layer This class is responsible to do Inserts, Updates and deletes to your data base This add method goes and inserts into data base At this moment I am not going to write any kind of data base code here I’ll just say console.writeline SQL server inserted This SQL server class This SQL server Data Access Class Layer is used inside this Middle Layer here Here I will create the object of the Data Access Layer Odal=new SQL server data access layer When anybody calls the add method of the customer I will internally call the Add method of the Data Access Layer We have a very very simple Three Layer Architecture Three Layer project here We have a UI then we have the Middle Layer i.e our customer layer and then we have a Data Access Layer which is SQL Server Data Access Layer In this UI developers create the object of customer Customer obj=new customer They set properties of the customer class must be this comes from text box but at this moment I will just keep it hard coded and they call the add method They call this Middle Layer add method The Middle Layer add method calls the Data Access Layer of the SQL Server Very very simple Three layer Architecture here and this is what is used in most simple projects what are created What is a problem with this Three Layer Architecture? One of the biggest problem with this Three Layer Architecture is Tight Coupling Tight coupling means for example you can see here customer class or this Middle Layer is actually using this SQL Server Data Access Layer Lets assume that some of your customer demand saying that our application should also support Oracle You will create a new data access layer called as Oracle Data Access Layer Then you will make changes into your customer class Tight coupling means when I make change at one place it actually goes and affects all over your application Remember, a good architecture is that architecture wherein if you make changes at one place it does not replicate all over the place for example If I make change in onemodule It does not starts affecting 10 or 15 module That’s a good architecture But in this case of you see for example added a Data Access Layer Oracle Data Access Layer What I have to do here is I have to create the object of the Oracle data access layer Depending on conditions he will call This condition can come from a config file This conditions can come from parameter table Depending on the condition he will call either the SQL server data access layer or he will call the Oracle data access layer Odalora.Add These conditions here at this moment I have just said true These conditions can come from config files It can come from parameter table and lot of things This conditions can come from anywhere Depending on that conditions he is calling up the SQL Server Data Access Layer This is SQL server or he will call up Oracle In simple words this is a tightly coupled architecture and that’s bad because If I add a new data access layer type I have to change my Middle Layer Changes will happen Some of the developer saying that there shouldn’t be any change It is not like that There should be least changes For example rather than changing at 10 places a good architecture will lead to changes in two places Changes will happen its not that changes will not happen For example if you add a delete functionality in your data access layer You won’t get automatically a delete button on the screen So changes will happen But the point is how least are those changes and that is important At this moment we have tightly coupled architecture If you want to move from this tightly coupled architecture to a loosely coupled architecture The first thing what we need to put here is a Interface A Interface a generic interface of a data access layer which can point towards either Oracle or either SQL Server The core thing for decoupling two layers is always a Interface The first step we have to do here is create a interface called as IDAL that IDAL will have a method called as a Add Let me minimize this Middle Layer here I’ll create a Interface Let me create a interface called as IDal which will have a method here called as Add This IData Access Layer will be implemented by SQL Server Data Access Layer It will also be implemented by Oracle Data Access Layer I have created a very simple interface here IData Access Layer which can point by the virtue of Polymorphism to either SQL Server Data Access Layer or to the Oracle Data Access Layer That would really minimize my code I have to only create or only point towards IData Access Layer Depending on situations I will either create a SQL Server Data Access Layer or I will either create a Oracle Data Access Layer I can remove this code from here here the object creation is happening Here I will call OData Access Layer.ADD You can see here My customer is actually pointing towards IData Access Layer Depending on my configurations or my parameterization whatever I do It either goes ahead and creates an SQL Server Data Access Layer or either it goes ahead and creates a Oracle Data Access Layer this is happening because of Polymorphism Remember, in polymorphism the same object can point towards different objects under different conditions For example, depending on the condition it is either becoming a SQL Server Data Access Layer or either it is pointing towards a Oracle Data Access Layer Is this a Decoupled architecture? And the answer is absolutely NO why? You can see we have lot of concrete classes reference in the customer class In this customer class I am referencing the SQL Server Data Access Layer and I am referencing the Oracle Data Access Layer In other words Somebody goes and adds a new Data Access Layer like My SQL I have to again go and do the modification of my Middle Layer In other words what is really happened is Probably where we were writing four lines of code It has been Minimized to two lines of code Where I was creating the objects of Oracle and SQL Server It has minimized those lines of code Still it is not a decoupled architecture Its just a coupled architecture Its a tightly coupled architecture If you watch very closely the reason why the current architecture is tightly coupled or why the customer class is tightly coupled with the data access layer is because of this new keyword This Middle Layer or the customer class is doing too much work specially he is doing the work of object creation If we can somehow remove this object creation of this data access layer from this customer object or from Middle Layer Then we would go towards a decoupled architecture In other words if this customer class references the IData Access Layer and there is no reference of SQL Server Data Access Layer or Oracle Data Access Layer Then we are moving towards some solution The first thing we should get rid of this object creation activity what this customer class is doing Remember this customer class or the middle layer is suppose to do validations is suppose to do business logic and not object creation and not deciding that he has to create a SQL Server Data Access Layer or Oracle Data Access Layer I would like to get rid of this object creation completely from here I’ll do a delete here Currently if you see this current situation the customer class is just referencing this interface IDAL If you think from the customer class point of view He has become selfish he says that I will do just my work that means he is trying to follow SOLID principles single responsibility principle saying that I will do only one responsibility i.e business logic and validation I am not the guy who will decide data access layer SQL Server Data Access Layer Oracle Data Access Layer that has to be taken care by someone we will create a constructor we’ll say that Somewhere from outside somebody will pass The IData Access Layer object you can see what I am doing is from the customer class prospective I have become selfish What I have done here is The customer class is exposing out a constructor and he says that someone else who is that someone else we have no idea of it The person who is going to instantiate me has to pass me that he wants to invoke me using the SQL Server Data Access Layer or he wants to invoke me using Oracle Data Access Layer In simple words The creation of the Data Access Layer object is now the responsibility of the caller who invokes the customer class Currently this customer class is getting invoke from this UI here i.e through our static void main It now becomes the responsibility of the UI to invoke the object Whoever invokes the customer object he has to pass to him saying that This customer object has to be invoked using the Data Access Layer SQL Server Data Access Layer or it has to be invoke by using the oracle Data Access Layer Still our dream of achieving that decoupled architecture is far away With this exercise what we have done now is we have just passed the bucks around In other words the object creation was first happening inside the customer class Now happening inside the User Interface really things have not changed If I add a new data access layer I have to change the user interface code If I add a new Data access layer I don’t have to change anyone of these layers that’s what a decoupled architecture would look like The only way to achieve this only by giving object creation activity to some external third party framework A framework which is configurable which is easy to use If we do this object creation activity inside our code That code can be either the Middle Layer or it can be User Interface Then we would be just passing the bucks around we would not be able achieve our decoupling dream There are lot of frameworks out there which help you to do dependency injection For example we have Unity Application block which comes from the Microsoft Patterns and practices then we have the Manage Accessibility Framework MAF which is a part of your .Net framework we have Ninject etc At this moment I have chosen Unity Application Block Because its a light weight a component and its been time tested for so many years I am going to use Unity Application Block here to do dependency injection In order to reference The Unity Application DLL The one way is that you go to you search for unity application DLLs download them as a rar format the DLLs downloads it in your folder unzip the rar add the reference etc lot of work Other ways is by using Nuget In case you are new to Nuget my suggestion is to go and watch the video of Nuget What exactly it is and how it helps you to add references to the third party DLLs At this moment I will quickly go to the Nuget here Go to tools here click on tools I’ll click on this Nuget packet Manager and i will say manage Nuget packages for solution you can see that my Nuget has opened here What I have done is I have clicked on this search box here I have typed Unity You can see the first search on this Unity here On this unity click on Install You can see it is now installing I will say okay I accept the licenses Now what happens with Nuget is automatically the DLLs are downloaded it adds the references to your project everything is automatic here Rather than going and downloading by using the traditional way you can use Nuget here it is much better its easier and also it is more accurate as compare to doing things manually Let me go to my solution explorer here On my solution Explorer there are Three DLLs added You can see this Microsoft.Practices.Unity Microsoft.Practices.Unity.Configuration There is Microsoft.Practices.Unity.RegistrationByConvention This three DLLs are added over here We are all set In other words DLLs are added now we have to go and write the code Before I move ahead and I write some code to do the injection or before I start demonstrating code using unity Let me explain you what this three DLLs too Microsoft.Practices.Unity and Microsoft.Practices.Unity.RegistrationByConvention both this actually do the injection They will actually create the SQL server object that inject into IData Access Layer They will actually create the oracle object and inject into IData Access Layer Unity also provides a way out where you can write your configuration into a XMLFile That XML file can be App.config it can be Web.config or you can also treat your own XML File In this XML file probably you can define configuration like saying that inject SQL Server Data Access Layer into IDAL Interface Inject Oracle Data Access Layer into IDAL Interface Such kind of configuration you can define into the XML File to read that XML File this DLL i.e Microsoft.Practices.Unity.Configuration will help you out Microsoft.Practices.Unity and RegistrationByConvention they actually do the injection and this Unity.Configuration reads from the XML File the configuration applies it to your code Let us go ahead and start writing code First thing is First thing first we have to import the namespaces At this moment I am not going write configuration in a XMLFile I don’t want that configuration Unity.Configuration reference I do want the reference to the unity namspace why? because at least I want to do the injection In the next part of the video we will see that how we can put the configuration into a XML File and then apply it to your project I have imported the Microsoft.Practices.Unity namespace here The next thing is I need to create a object of a container I need to do something like this I’ll say here IUnityContainer obj Container=new UnityContainer I will explain you what exactly this container does Let me just write the code and I will explain you from the code itself what this concept of container is Unity Application Block is a third party framewrok In other words it is not a part of .NET Framework or it is not a part of your application directly It has no idea what kind of classes your object has For example Unity Application Block does not know you have a customer class It does not know that you have SQL Server Class or a Oracle Data Access Layer Class The first step is to make aware of your project classes to the Unity Framework and this is done via using the container You need to add all your classes to the container Unity framework will look at the container he can then figure out what kind of objects it can create on runtime You can think about this Unity Container as a basket, a bucket, a container whatever you want to name it Wherein you need to register your objects and then when you say I want this object The Unity Application Block will go to the container create that object and give it back to you Let us go ahead and register our customer class and register our SQL Server Data Access Layer Let us go ahead and register our Oracle Data Access Layer Register our objects inside this container To register the objects you have to say objContainer .Register I want to register first thing is customer class You can see I have registered my customer class I have made the Unity Application Block aware that I have a customer class Also let us go ahead and register Oracle object or I’ll say SQL Server Object The Data Access Layer objects Remember, there are two kind of classes or objects I’ll say One is your main class like customer When you register your customer class There is no dependency injection happening on the customer class When you are registering a SQL server class or when you are registering a oracle class That’s what is actually going to get dependency injected In other words those are the dependent objects When you are registering objects which are dependent on each other on which the actual dependency injection is going to happen We have to say here I want to inject into IData Access Layer You can see there is a From here and a To Into IData Access Layer I want to inject a object of SQL Server Data Access Layer You can see here when you registering the dependent object You have to tell what is a Interface What is a concrete object which you want to inject In the same way I’ll say register type again IData Access Layer Also I want to inject The Oracle Data Access Layer Once you have loaded or I’ll say you have registered the classes in the container The Unity Application Block is now well aware of what kind of types your application has At any given moment of time Its either in the UI or its either in your Business Layer or Middle Layer I will say You can demand for objects To demand for objects You can call the resolve method I can say here something like this container Remember, you have to go via the container You register objects into the container If you want to get the objects you have to again get form the container I’ll say here Resolve This Resolve is like get in the objects can you give me out a customer object Let me put a debug point here let me run this console application I am going to run this console application here in a debug mode Now I am in a debug mode My application has ran The first three or four lines of code has registered all our classes in the container When I say Resolve It actually creates a customer object When I do a resolve here You can see that he created a customer object and inside that customer object This is my customer onject inside this customer object he has injected Oracle Data Access Layer Automatically the injection is happening via the Unity Application Block If you see this current situation The injection is neither done by the console application i.e the UI it is neither done by The Middle Layer it is neither done by The Data Access Layer It is done by someone else This first three or four lines of code you must be thinking that I have written in the User Interface You can take this code and you can write it anywhere else It does not have to be in UI At this moment this code is in the UI It can be on some startup event For example let say if it is ASP.NET then probably this code can go in the global.asax file If it is WPF then this code can go in app.xaml.cs This startup code can go anywhere It is not necessary it should be a part of The User Interface When you talk about console application the startup always happens from the Static Void Main That’s why I put the code here In actual enterprise application like WPF or ASP.NET They always have there own startup event and this kind of code actually can go in those startup events They don’t have to be a part of User Interface If I continue ahead if I do a F11 you will see that its actually making a call to the Data Access Layer of Oracle and my code runs successfully If you see this current architecture state it is a decoupled architecture Why? Because The User Interface at this moment it does not have to be aware of SQL Server Data Access Layer and Oracle Data Access Layer Again I am repeating Lot of people must be thinking that why this SQL Server DAL and Oracle DAL is written in the Static Void Main We can always take this code and put it somewhere else And that somewhere else can be anywhere It can be The Global.ASAX start event It can be your app.xaml. application load event or whatever It does not have to be here In the UI I have to just say container.resolve and I have to resolve the class and the injection will happen automatically If you see the current architecture state it is completely decoupled If I add a new Data Access Layer My User Interface it does not have to be aware of that new data access layer Let me define dependency Injection again When I started this video I talked about the definition of dependency injection At that time it was not so cleared I wanted you to walk through this whole road map through this whole thought process of how right from interfaces then used this ready made framework to do dependency injection I wanted you to go through that whole exercise I think we have done it now Let me again go and define dependency injection you can understand it better Dependency Injection is nothing but its a technique its a technique by which we can inject dependent objects of a class For example if you see in this example we actually injected The Data Access Layer Object using the container or using the unity application block We created the object of the unity application block container These are the objects and the unity container Whenever he say give me customer he injected the Oracle Data Access Layer object and he give it out to you Again I am repeating dependency injection is nothing but its a technique by which we can inject dependent objects of a class and by doing so we are able to achieve Decoupled architecture In other words when you say decoupled architecture when you make change at one place You don’t have to go and change all over the place For example in this case when I added a new data access layer If I add a new data access layer now I don’t have to make any kind of code changes on my UI I hope that you enjoyed this video In this video we discussed about DI and we also spoke about how to implement DI using unity application block There are couple of problems which yet has to be resolved First one is if you remember when i actually resolved this customer object by using the unity application block It automatically injected the oracle data access layer If I want to inject the SQL server data access layer and next question is why he did not inject the SQL server data access layer and why did he inject the oracle data access layer This register only registers the object It does not say that which object has to be inject where If I want to do a conditional resolve In other words depending on situation I would like to create a object of SQL server and inject it inside customer and depending on some other conditions I would like to inject a oracle data access layer object and inject into customer If I want to do conditional resolve How do I do it? If you see at this moment all this code of registering the objects is inside our C# How about taking this code and putting it into XML file If you are able to do that then all our types will be loaded from XML In other words I really don’t have to go change anything in my code That is the second thing I want to do The third thing is I would like to manage the object lifetime I don’t know that what is the lifetime of this customer object and how does it works How can we manage the object lifetime inside a unity application block These are some questions which are still unanswered That’s what we will do in the next part of the video If you really think what we doing over here is good great and useful You have to take this video and share it on your twitter account on your facebook account on your linkedin wherever spread the knowledge share knowledge get knowledge and I hope that you will all prosper That also gives us lot of encouragement it also gives us lot of support and it also send us message saying that what we are doing is useful and we should continue doing that Thank You So Much

100 thoughts on “Dependency Injection using Microsoft Unity Application block ( DI IOC) – 30 minutes training”

  1. Benny Blanco from The Bronx

    This is the best video about dependency injection I have found out there.
    Your videos are very educational and keep up the good work. Congratulations !!!

  2. Excellent video. Best short video for dependency injection. Thanks a lot and let us know when is the 2nd part releasing 🙂

  3. Jose Enrique Mariño Iglesias

    Hi, very good video, but you said you will show other way to configuration in the second part of the video but i can't find the second part. Could you please show me the link. Thanks you so much.

  4. Hi,
    Here you can you use a simple Conditionnal Resolution via Unity, related to the example of the above nice Video:

    IUnityContainer objContainer= new UnityContainer();
    objContainer.RegisterType<Idal, OracleDAL>("oracle");

    var Sql = objContainer.Resolve<Idal>("sql");
    var cust= objContainer.Resolve<customer> (new DependencyOverride(typeof(Idal), Sql));
    cust.CustomerName = "inject Dependances";

  5. Hi. Very grateful for your efforts. I can say I understood right from the first video. Please consider doing the next installment. it would be very helpful for a lot of us. Thanks again.

  6. Do I have to register both IDal implementation and how does the UnityContainer decide which IDal implementation to inject to the Customer constructor???

  7. hi brother it's nice explanation… in mycompany I need to implement this concept as per my architecture advice .. could you please share second part of this video for condition resolve

  8. Great Video , But I need to look into second part when I visit it just show me list of video but where is exact location of second part , i think this is same like any discount on any product , if you look any product then one is free but for most like product you have to pay , but that also fine but give me exact link..

    Thanks a lot for sharing such a lovely video… Thanks a lot.

  9. Nice video.
    Basically you need to 1) nuget unity, 2) register types somewhere at your startup and 3) use Resolve instead of new()… and that´s it

  10. Hi how do i call SQL or Oracle Add Method when calling Customer Class Add Method, because at now it will call only last register IDal Add method

  11. One small comment: If you stop repeating same and quite obvious things you can make more efficient videos. Keep doing good work !!

  12. Hello nice turorial, but a very simple and maybe stupid question for advanced developers, How can we create a condition to choose Oracle or SQL object? becase I don't see the advantage of this, I would like to use same interface for diferent classes using Unity but in this example Oracle will be always selected, I dont see the advantage. Please help a beginner programer
    . Thanks

  13. hi can you tell me – from where obj.container.resolve<customer> came to know that it is calling sql or Oracle???? it is used defined classes… how does utility came to know these??

  14. Doesn't registertype basically new up the classes? So why not create a class that returns each type of interface? It seems like unity is doing the same thing just behind the scenes.

  15. According to DI every module should be decoupled, it has been achieved through the above example but its not a good architecture here. As in Main method i.e. UI project they will require the SQLServerDal and OracleDAL class references, these class references should be in BAL only, it should not be extended till UI, and UI project should have only BAL reference.

  16. Not dividing the project into separate projects for the different application layers significantly reduces the effectiveness of this video. New users need to understand what references need to be set in each of the different layers.

  17. Question –
    at 26:20 mins — instead hwy not it create a customer object without constructor ?- why it automaticlly created with constrcuor and that to with OracleDal- we disn't called any injection for the constructor param wight ?

  18. Beginning of this video was too good but at the end confused totally !! At least you should make us clear why it is calling last registered and how to control it. Frankly speaking it's confusing us. Will you be able to make a fresh video and explain clearly.

  19. You say GO and watch IOC first! Go ! then when i search for it in your list nothing comes up…. ? Pleas add a link of what you refer too.

  20. how to handle many business objects such as customers, suppliers, agents etc in dependency injection? Should we add every object in the container

  21. IDal Idal = new SqlServerDel();

    a parent class reference variable can point to child class object is called polymorphism

  22. thank you so much it was a pretty good tutorial and i learned how to decouple an application by implementing DI IOC injections

  23. This helped me understand Unity and Dependency Injection better than most of the explanations found on the web. Simple and straight to the point.
    Thank you.

  24. IUnityContainer objContainer = new UnityContainer();



    objContainer.RegisterType<IDal, EmployeeOracleDB>();

    From the above how can I have to use SQL Server DB connection how should I gain control over it.

    I've tried some modification as below:

    objContainer.RegisterType<IDal, EmployeeOracleDB>("EmployeeOracleDB");

    But how Customer object knows which DB connection to select as it is returning lastly added Class in the container ?

  25. Hi, thanks for making this video. I finally learned how DI works. But now I want to learn more and I can't find the next part of this video. Could you please share it?

  26. Dependency Injection Lay Man Terms. A charging adapter with usb port has inverse dependency with pendrive. Direct dependency means only a pendrive can be plugged into the charging adapter. Usb (universal serial bus technology is called the interface) . The company that made the adapter exposed an interface. Pendrive making company injected the dependency which is the pendrive device. Since the charging adapter has reversed or inversed the dependency you can now plugin a mouse or a keyboard or anything to this adapter. Thats it

Leave a Reply

Your email address will not be published. Required fields are marked *