Saturday, June 27, 2015

Dependency Injection with Autofac : Constructor Injection

Recently I’m playing with Autofac and I’m having fun with it. This blog post a part of same series. In this blog post we are going to look into how we can do constructor injection with Autofac. If you are not familiar with Autofac you can go through my introductory blog at following location.

Dependency Injection with Autofac: Getting Started

In this blog, We are going to see how we can do constructor injection with Autofac. So for that I’ve created a small console application. After creating a application, first thing you need to do is to add reference of Autofac via Nuget Package. You can do that via following nuget package.



Now it’s time to write some code. I’ve created a sample basic “Employee” model class like following.



After that I’ve created a interface “IEmployeeRepository” which has one method to print employee and expects Employee object parameter.


And following is a implementation class for Employee Repository.


Now it’s time to write Employee Service class code like following.


If you see above class carefully, You can see that it’s expect a constructor parameter of Employee Repository parameter and there we need to constructor injection.  So let’s write some Autofac code for constructor injection like following.


Here in the above code, You can see I have “BuildContainer” static method. Which created a Container Builder object and It’s register type of employee repository and employee service and it’s return a container object. In main method code I’ve resolve employee service class object with container and it’s automatically inject our constructor requirement of employee service class. Then I’ve created a employee class object and print it with print method. Once you run the application. You will get following output as expected.

constructor-injection-autofac-output

That’s it. You can see it’s very easy to do constructor injection with Autofac. In future post we are going to look at some other features provided by Autofac. Stay tuned for more.
You can find complete example of above blog post at following location on github- https://github.com/dotnetjalps/AutofacSamples
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews