Showing posts with label Autofac. Show all posts
Showing posts with label Autofac. Show all posts
Sunday, July 5, 2015

Dependency Injection with Autofac: Keyed Registration

This will going to be a fifth post in my Dependency Injection series with Autofac. If you have not gone through all the previous post of this series then I would like to encourage you to go through it. Following is a list of blog posts.
Dependency Injection with Autofac : Getting Started
Dependency Injection with Autofac : Constructor Injection
Dependency Injection with Autofac : Module Feature
Dependency Injection with Autofac : Registration Ordering
Dependency Injection with Autofac: Named Registration

Keyed Registration:

There are multiple ways of register and resolving type in Autofac and keyed registration is one of them. Just liked named registration here you can resolve a type with a key. That key can be a valid C# object. Let’s create a sample console application for it. I have added reference of Autofac via NuGet package as did in my previous blog post. Following is a Customer class that I’ve created for the Keyed registration demo.


After creating Customer class following is a code that I’ve written for demo of Keyed Registration with Autofac.
If you see above code carefully, You can see that first I have created a object of customer as keyCustomer then I’ve register customer type with that keyCustomer Object.  After that I’ve resolved customer with that keyCustomer object and assigned few properties and then Print that customer with “PrintCustomer” object.
One thing to note that when you register type with Keyed Registration It can not be resolve without it. You can only resolve that type with same key you have registered.
Now when you run this application. You will following output as expected.

autofac-keyed-registration-output
That’s it. Hope you like it. Stay tuned for more!!.
You can find complete source code of this Autofac series on Github at - https://github.com/dotnetjalps/AutofacSamples
Share:
Friday, July 3, 2015

Dependency Injection with Autofac : Named Registration

I’m really having fun with Autofac and It is a great IOC container.  As its tag line suggest it it a addictive IOC container.  This post will be a part of Autofac series. If you have not gone through my previous blog post then I would suggest you go through it. Following is a list of blog post I’ve written for Autofac series.

Dependency Injection with Autofac : Getting Started
Dependency Injection with Autofac : Constructor Injection
Dependency Injection with Autofac : Module Feature
Dependency Injection with Autofac : Registration Ordering

Named Registration:

Named registration can be very useful when you have to create multiple object of same type with different states. Autofac provides that functionalities with Named Registration. I’m going to create a sample console application and added Autofac via Nuget package.  To demonstrate named registration I’ve created customer class like following.


Now let’s write some code to create named instance like following.
As you can see in above code, I have created a named registration with build container and then I have resolve the instance with same name which I have done registration for it. Then I populated properties of Customer and Printed that customer with “Print” function.
One thing to note here that when you register types with named instance then it can not be resolved without name. If try to resolve it it will give error.
Now when you run this application. It will print Customer as expected.

Autofac-named-registration

That’s it. Hope you like it. Stay tuned for more!.
You can find complete source code of  this Autofac series on Github at - https://github.com/dotnetjalps/AutofacSamples
Share:
Tuesday, June 30, 2015

Dependency Injection with Autofac: Registration Ordering

This post will be part of on going series for Dependency Injection with Autofac. If you have not gone through my previous post I would encourage you to go through it. Followings are links for that.

Dependency Injection with Autofac – Getting Started
Dependency Injection with Autofac – Constructor Injection
Dependency Injection with Autofac- Modules Feature

In this this blog we are going to learn about Registration ordering in Autofac.  If you register same interface multiple times then by default the last registration will be preserved. So when you resolve things it will be resolved by last registration. You can also prevent that via “PreserveExistingDefaults” method which is a second behaviour where first registration will be preserved. We will look both in details in this post.

Registration Ordering:


To demonstrate registration ordering, We are going to create a simple Employee class like below.

After creating a Employee class following is a code for my console application.

If you see code carefully, The important thing is two functions “DefaultBehaviour” and “AnotherBehaviour”. First function I’ve register two employee object one by one then. I tried to resolve employee object and with the help of "PrintEmployee" method I have printed Employee object.  Here I’ve used default behaviour so it will print secondEmployee as last registration will be resolved.

While in “AnotherBehaviour” function, I have used “PreserveExistingDefaults” function while registering secondEmployee object. So it will preserve first registration. So when you resolve object it will resolve first registration. So when you print employee object with “PrintEmployee” method it will print firstEmployee object.

When you run this console application. Following will be output as expected.

autofac-registration-ordering

That’s it. Hope you like it. Stay tuned for more!.
You can find complete source code this Autofac series on Github at - https://github.com/dotnetjalps/AutofacSamples
Share:
Sunday, June 28, 2015

Dependency Injection with Autofac : Modules feature

I’m having fun with Autofac as IOC containers and this is third post in series. In this blog post we are going to learn about Autofac modules. If you have not gone through first two blog posts then I would encourage you to go through it. Followings are link for that.

Dependency Injection with Autofac- Getting Started
Dependency Injection with Autofac – Constructor Injection

What is Autofac Modules?

Autofac modules provides greater flexibility  for structuring large application. Register all the component in single class will work for small applications. But for larger applications that will be quite difficult class. In this situation Autofac modules can help.  Autofac modules allow us to break registrations of component in different classes. Then later all you can load all the modules at single places.

So what we are waiting for, Let’s write some code to demonstrate the power of Autofac Modules. For that I’ve created a simple console application called “AutofacModules” and added Autofac nuget package to get reference of application. In this application we are going to create two separate module for “Student” and “Teachers”. So lets start by creating student model class like following.


Following is a student repository interface which contains a "Print" Method to print Student.
 And here is the implementation for Student Repository Inteface.

Now it's time to create Teacher model class like following.

Following is a interface created for Teacher repository which contains "Print" Method to print Teacher.
And here is the implementation of Teacher repository interface.
Now we are done with creating basic classes and interfaces for Student and Teacher It's time to create a modules for them. To created a module for them we need to create a separate class for Teacher and Student Module which got inherited from the Autofac module class. Following is a code of Student module.
And same for teacher module.
 If you see code of both classes carefully then you will realize that it is inherited from the Module classes and It's got a Load method override where we have done registration of repositories. Now our modules are also ready so It's time to write our main console application code. Following is a code for that.
If you see above code carefully the important thing is "BuildContainer" method where I've registered our module with RegisterModule method.Rest I have created teacher and student object and created object with Autofac Container and print respective objects. When you run application following is a output as expected.

autofac-module-console-application-output

That’s it. Hope you like it. Stay tuned for more post about Autofac features.
You can find whole source code of this Autofac series at Github on following location -https://github.com/dotnetjalps/AutofacSamples
Share:
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:

Dependency injection with Autofac : Getting started

I have been using dependency injection a lot in my projects. As it’s provide great flexibility to wire up things. Recently in free time I have been looking into some of open source architecture like Orchard and Nopcommerce. Both are using Autofac as dependency injector. As this IOC container are used in one of top successful project I got interested in Autofac and I started learning Autofac. I thought it will be a good idea to start a blog series for my learning so other can get benefit of it.

What is Autofac?

As per Autofac.org a site for Autofac
Autofac is an addictive Inversion of Control container for .NET 4.5, Silverlight 5, Windows Store apps, and Windows Phone 8 apps.
It is used in lots of application and one of the most popular IOC container in .NET world.  As per official documentation here is the basic pattern for integrating Autofac in your application.
  • Structure you application with Inversion of Control in mind
  • Add Autofac references( I prefer it using Nuget Package).
  • At application startup create a container builder
  • Register a component
  • Build container and store it for a later use.
  • Create lifetime scope of container during application execution.
  • Use lifetime scope to resolve instances of application.

Autofac Example:

So what we are waiting for, Let’s create a simple example. I’m going to create a sample application like following.

AutofacBasicConsoleApplication

After creating application, I have created a my interface IPrintService as following.
namespace AutoFacBasic
{
    public interface IPrintService
    {
        void PrintSomething(string text);
    }
}

Here is the implementation of interface in class like following.
using System;

namespace AutoFacBasic
{
    public class PrintService : IPrintService
    {
        public void PrintSomething(string text)
        {
            Console.WriteLine(text);
        }
    }
}

Now, We have done with basic stuff so it’s time to wire up component with Autofac. To add references for Autofac I’m going to use following nuget package.

nuget-package-autofac

After adding a Autofac reference via nuget package. I have written following code for that sample console application.
using Autofac;
using System;

namespace AutoFacBasic
{
    class Program
    {
        static void Main(string[] args)
        {
            //registering interface with class that implemented
            var builder = new ContainerBuilder();
            builder.RegisterType<PrintService>().As<IPrintService>();

            //Resolving inteface with autofac
            var container = builder.Build();
            var printService = container.Resolve<IPrintService>();
            printService.PrintSomething("Hello World");
            Console.ReadKey();
        }

    }
}

Here in the above code, If you see carefully. First I have created a object of Container Builder and then I have register type with print service. Then I have build container builder to get container object. After that I have resolved print service with container and get the object of printer service. Then I have printed Hello world with PrintSomeThing method. When you run application. Here is the output as expected.

autofac-console-application-output

That’s it. You can see how easily we can wire up things with Autofac. In future posts we will see some advance features of Autofac. Stay tuned for more!!.

You can find complete source code of this application at following location at github- https://github.com/dotnetjalps/AutofacSamples/
Share:

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