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.


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-

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 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.


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)

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.


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();

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


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.


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-
Wednesday, June 24, 2015

Completed 725 blog post and still counting

I’m not a fan of counting milestones but today it was huge one so I could not resist myself to write a blog post about it. Today this blog has been completed 725 Blog post.

I still could not believe this blog has come so far!. This will would not have been possible without you guys.

I promise that I try to keep updated this blog in weekly.  Also on this occasion I would also like to thank my family. Specially my wife who is continuously supporting me and sacrifice her time for my blog post.

Thanks you all again! . Also today I have changed my blog theme to a modern look. Hope you like it. Stay tuned for more. Keep reading my blog. 
Saturday, June 13, 2015

Double quotes not working with Visual Studio

Recently, In one of the development machine with Windows 7, I was having strange problem with Visual Studio 2013, When I type double quote first time it was not there and then after once again type I type then it was there. I was wondering what is going on. After digging into little deep, We figure out it was due to language settings and that is creating problem. After fixing languages I was able to fix this issue. I thought it will be good idea to write a blog post about it. So other can be benefits also.

So problem I was having is I have to type double quotes two times. To fix that problem first thing you need to do is Goto  control panel-> region and language options. There you need to go to Keyboard tab. In windows 8.1 Go to search and search for language preferences.

Once you go to language preferences select English US Keyboard. Set that as default.
Now once you are done with your control panel settings. It’s time to make settings changes in Visual Studio. To Change the settings in visual studio go to Tools –> Options –> Environment Settings –> International Settings.
Wednesday, May 13, 2015

Visual Studio 2015 Github tools

I love open source and that’s why I’m making all the source code of my blog post on Github. Now with Visual studio 2015 RC Microsoft and Github released a GitHub tools for visual studio. So now you can directly interact with your Github repositories from team explorer itself. Working with Github never be easy now.

Once you install, Github tools for Visual studio with visual studio 2015 installation. It will be available on Team explorer like below.


Saturday, May 2, 2015

My sample code for 2015 Global Azure Bootcamp Ahmedabad

Lots of people ask for my sample code application for my presentation on “Azure Storage Services”.  So here is source code(Sample application) for 2015 Global Azure Bootcamp, Ahmedabad.

Source code of sample application for  2015 Global Azure Bootcamp , Ahmedabad:

You can find source of sample application which I have created at following location on GitHub.

Azure Frequently Ask Questions: How to create a storage account with new portal

After presenting About Azure Storage Services at Global Windows Azure boot camp at Ahmedabad. I got lot of feedback and questions. One of the frequently asked question was how we can create a storage account with new Azure portal Preview. So I thought it would be a great idea to write a walk through post for it.

As you know, Before few months Microsoft has launched a new Azure portal in preview mode. It’s amazing there are lots of features available. You can find azure portal at You can do lots of stuff and monitoring that were not possible with current portal. I've tried and really like it. Please do try it and tell community about your feedback.

How to create a storage account with new azure portal:

So what we are waiting for let’s start our walk through of creating a storage account with new portal. So once you put url in browser it will be ask for login with your azure live account.

Sunday, April 19, 2015

Structure and Operator overloading in C#

Recently I have been playing with structure and It’s fun. In this blog post we are going to learn how we can use operator overloading with structure in C#.  You can find my blog post that I have already written about structure  at following location.

Structure in C#
Structure with constructor in C#
Structure with Interface in C#

So as usual I've created a console application to demonstrate operator overloading in C#. Here I have created a structure with equals operator overloading and following is a code for that.

Structure with Interface in C#

Recently I have been playing with Structure and it is fun. I have written couple of blog post about structure. Following are links for that.

Structure in C#
Structure with constructor in C#

In this blog post we are going to learn how we can use structure with interface. So like earlier example I’ve created a console application. Now it’s time to write interface which we can implement with structure. Following is a code for that.
using System;

namespace StructureWithMethodAndInterface
    interface IPrintable
        void Print();
Here you can see that I have simple interface IPrintable which has simple print method. Now let’s create a structure which implement this interface. Following is a code for that.
Friday, April 17, 2015

Structure with constructor in C#

Before some time , I have written basic introduction post about Structure in C#. In this blog post we are going to see how we can have constructor with Structure. As we all know structure is a value type so it stored on stack. So let’s create a structure like follow with constructor.
public struct Customer
    #region Fields

    public int CustomerId;
    public string FirstName;
    public string LastName;


    #region Constructor

    public Customer(int customerId, string firstName, string lastName)
        CustomerId = customerId;
        FirstName = firstName;
        LastName = lastName;

Here you can see I have created Stucture with parameter. As we all know structure is a value type so when initialize the it at that time we need to give values to its elements so that’s why default constructor without parameter is not supported in C#.

Wednesday, April 15, 2015

Structure in c#

In this blog post we are going to learn about Structure Data structure in C#. In C# Structure is value type which stores on Stack. It is a composite value type that contain other types. You can also create object of structure like class. In C# structure can  contains fields, properties, constants, constructors, properties, Indexers, operators and even other structure types.

So enough theory. Let’s create a sample console application to learn about structure.


Tuesday, April 7, 2015

Entity Framework Code First and MySql on Azure

We have used Entity framework with SQL Servers mostly. In this blog post we are going to see how we can use Entity framework with MySql on Azure.

How to create MySql database on Azure:

On azure MySql is not maintained by Microsoft itself. It is provided their partner cleardb. So You need to search at Azure Market Place and then add it like below.


Sunday, April 5, 2015

Best coding standards checklist for C# and ASP.NET

Before some time I have written a blog post about coding standard Why coding standards are important?. It was appreciated by lots of people and few people asked me whether do you have coding standard checklist or not? So Today, In this blog post I’m going to shared few link for coding standard checklist which I follow.

Aviva C# coding guidelines:

An awesome guideline for the C# 3.0,4.0 and 5.0. It’s very good and open sources. You can find that following link on code plex.

Do Factory do and don’ts for C#:

A great list of do and don’ts of C# coding standards that all we should follow.

Encodo C# Handbook:

It’s having so many coding standard and most of relevant to naming conventions and formatting. You can download that via following link.

Microsoft All one code framework:

I have been using this for a while. It’s an awesome library which display best practices how we can write code.

There are lots others are also available but I think it’s if you follow and practice above mentioned resources your code will be perfect.

Entity Framework Internals: Connection Resiliency

When you use cloud services to deploy your application and database it might be possible that transient connection will be a problem between database server and web servers. When you use on premise servers that uses the database server and web server on same data centre. When you use cloud there will be huge infrastructures and you never know where it is deployed even if it deployed on same data centre there will more connection like network load balancers etc. When you use cloud services that will be shared by lots of users which means its responsiveness can be affected by them. And your access to the database might be subject to throttling. Throttling means the database service throws exceptions when you try to access it more frequently than is allowed in your Service Level Agreement (SLA).

So in cloud service there will be transient problems which will be resolved in short period of time. So when you got such kind of errors then you can wait for some time and then you have retry. For that kind of operation Entity Framework provides connection resiliency feature.

The connection resiliency features must be configured for proper database services. It has to know which exceptions are likely to be transient problem and which exceptions are caused by our code. It has to wait for an appropriate amount of time between retries of failed operation. Also it has to try number of times before giving up.

Thursday, April 2, 2015

Quick Tip–How to get time difference in C#

Recently, One of the reader of this asked me about, how we can get time difference between two dates or two times? So I thought it will be a good idea to write a blog post about that. So that other use can also get benefit from that.

For that I have created sample console application like below.
using System;

namespace TimeDifferenceCSharp
    class Program
        static void Main(string[] args)
            DateTime firstDate = DateTime.Parse("12:50");
            DateTime secondDate = DateTime.Parse("10:40");

            TimeSpan difference = TimeSpan.Parse(firstDate.Subtract(secondDate).ToString());

In above example, If you see it carefully I have taken two dates with different time. Then I have used subtract method DateTime class to find different of both and then I parse it to TimeSpan class. After that I have printed hours and minutes for  via Console.Writeline method.

Now let’s run this application. You will see output as following.


That’s it.Hope you like it.

You can find complete source code of this blog post at github on-

Quick tip- How to change menu bar letter style in visual studio 2013 and 2015

When Microsoft has introduced, Visual Studio 2012 with Upper case menu, There were so many reactions from the developers. So with Visual Studio 2013 Microsoft has provided that settings to Turn of capital letters for menu. I have just came to know that accidentally. You can find that settings in Tools->Options-General settings.


Once you check it. Upper case will turn off like below.


That’s it. Hope you like it. Stay tuned for more!.
Wednesday, April 1, 2015

Entity Framework Internals: Private setters and private constructors

I have been heavily learning Domain Driven Design recently and In that there is a concept called “Anemic Domain Model” which we used to use in our project. In simple terms Anemic Domain Models are those classes that do not have any behaviour with them and most of created with properties. You can use them as container for your data from database. While Domain driven design is all about behaviours. So we need to make our models incorporate behaviours also which is called  “Rich Domain models”.

One of step to convert your Anemic Domain Models to Rich Domain Models is to create parameterised constructors. For example an Employee must have FirstName and LastName. So instead of doing validation at the insertion time on UI we should not allow Employee to be created without FirstName and Lastname. The only way to do this to make this properties setters private and assign value of those properties via parameters constructors like below.
public class Employee
        public Employee(string firstName, string lastName)
            FirstName = firstName;
            LastName = lastName;
        public int EmployeeId { get; set; }
        public string FirstName { get; private set; }
        public string LastName { get; private set; }
        public string Designation { get; set; }
Now, If you want to do DDD with any Object Relational Mappers there will be a problem as most of Object Relational Mappers create properties with public setters. Entity Framework is such a Object Relational mapper and I love to work with Entity Framework.

Thursday, March 26, 2015

Fluent Nhibernate : Create Table from Code(Class- CodeFirst)

Now days,  Convention over configured is more preferred and that’s why Fluent Nhibernate got more popularity Because with Fluent Nhibernate we don’t have to write and maintain mapping in xml. You can write classes to map your domain objects to your database tables. If you want to learn how we can do this with existing database and Fluent Nhibernate, I have also written a blog post about CRUD operation with Fluent Nhibernate and ASP.NET MVC . After writing this blog post I was getting a lots of emails about how we can create database from the Fluent Nhibernate as we can do same with Entity Framework Code First. So I thought it’s a good idea to write a blog post about it instead of writing individual emails.

How to create tables from class via Fluent Nhibernate:

To Demonstrate how we can create tables based mapping classes create we’re going to create a console application via adding new project like below.

Sunday, March 22, 2015

Entity Framework Internals: Enum Support

In .NET world, We all are using Enums in our code. It’s makes our code more readable then using hardcoded numbers of strings. Entity Framework 5.0 or higher version has support for Enums. In this blog post we are going to see how we can use Enums with entity framework.

We are going to create a console application to see how it’s works. I’m going to create a console application for the same.


After creating a application I’ve added Entity framework via Nuget package.

Saturday, March 21, 2015

Entity Framework internals :IEnumerable and IQueryable

Now days, Entity framework is one the most used ORM in .NET world. Still I can see lots of people confused with IQueryable and IEnumerable. If they dont' know what is difference between them then they are going to make mistakes .When you first look at it both looks same. But there are quite differences and If you don’t understands internals of it then it will impact your query performance also.

IEnumerable vs IQueryable:

Here is the basic difference between IEnumerable and IQueryable. When you write queries with IEnumerable it executes queries on Server and load data in memory and then filter data on client side. This will be a problem when you are fetching large amount of data. While IQueryable executes queries on server side with all filters and then load all data into memory.


Sound complex!. Let’s write a simple example to understand it better. I am going to create a simple table in database called student table.


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