Enabling log for Trace.Writeline

Download sample here

Just drop the dll in bin directory and place the below configuration in web.config


<trace autoflush=”true” indentsize=”4″>


<remove name=”Default” />

<add name=”rollingfile”

type=”Essential.Diagnostics.RollingFileTraceListener, Essential.Diagnostics”



template=”{DateTime:yyyy-MM-dd HH:mm:ss.fff} Thread: {ThreadId} {Message}{Data}”  />





JavaScript Design Patterns( Module pattern)

The Module pattern encapsulates “privacy”, state and organization using closures. It provides a way of wrapping a mix of public and private methods and variables, protecting pieces from leaking into the global scope and accidentally colliding with another developer’s interface. With this pattern, only a public API is returned, keeping everything else within the closure private.

Refer this link for more details


Transient Fault Handling and retry policy

  • Create a console application 
  • Add nuget package using  package manager console
  • Install-Package EnterpriseLibrary.TransientFaultHandling

  • Copy the below code 

//Defining RetryPolicy
class Program
const int RETRY_COUNT = 5;

static void Main(string[] args)
var retryStrategy = new Incremental(RETRY_COUNT, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2));

var retryPolicy = new RetryPolicy<CustomTransientErrorDetectionStrategy>(retryStrategy);

catch (Exception e)

// The block of code might throw exception
static private void NavigateTo()
Console.WriteLine(“Trial @ :” +DateTime.Now);

WebClient wc = new WebClient();


//Implement the ITransientErrorDetectionStrategy interface
internal class CustomTransientErrorDetectionStrategy : ITransientErrorDetectionStrategy
public bool IsTransient(Exception ex)
if (ex is WebException)
return true;
return false;


NavigateTo method will loop 5 times as it throws exception due to temp.txt file unavailability.

If we keep the temp.txt file with some content it executes one time.


Dependency Injection in C#

Mostly in ASP.NET MVC applications we could find this kind of implementation.

Follow the below blog


Using above as reference

Dependency Injection (DI) is a design pattern that takes away the responsibility of creating dependencies from a class thus resulting in a loosely coupled system. In order to understand DI you need to be aware of the following terms:

  • Dependency
  • Dependency Inversion Principle
  • Inversion of Control (IoC)

Let’s assume that you have a simple C# class as shown below:

public class Customer


           private DatabaseHelper helper; 

           public Customer()


              helper = new DatabaseHelper();



The Customer class declares a variable of type DatabaseHelper. The DatabaseHelper class is supposed to be doing some database operations such as SELECT and UPDATE. The constructor of the Customer class instantiates the DatabaseHelper class and the instance is stored in the helper variable. In this case the Customer class is dependent on the DatabaseHelper class for its functioning. Thus DatabaseHelper is a dependency of the Customer class.

The problem with the above design is that the Customer class and DatabaseHelper class are tightly coupled. If you ever need to substitute DatabaseHelper with some other class (say XMLHelper) then you will have to change the code of the Customer class since it directly instantiates the DatabaseHelper. To help avoid this, tight coupling Dependency Inversion Principle (DIP) is used. The DIP states that – High-level modules should not depend on low-level modules. Both should depend on abstractions. That means Customer should not depend on a concrete implementation (DatabaseHelper) but rather should depend on an abstraction. At code level this means the Customer class won’t have a variable of DatabaseHelper type, instead it will have a variable of some interface (or abstract class) type. This is shown below:

  1. public class Customer
  2. {
  3. private IStorageHelper helper;
  5. public Customer()
  6. {
  7. helper = new DatabaseHelper();
  8. }
  9. }

Now, the Customer class uses a variable of type IStorageHelper interface everywhere. IStorageHelper is supposed to be an interface that is implemented by the DatabaseHelper class and all such classes. Thus most of the code of the Customer class is now using an abstraction in the form of IStorageHelper.

Although the above code is better than the original implementation, it still has a problem. The helper variable is still instantiated inside the Customer class. This problem arises because the Customer class is responsible for creating its dependency (DatabaseHelper). The Inversion of Control principle (IoC) comes in handy in such cases. IoC states that the control of creating the decencies should be with the external system rather than the class itself. In the above example this means that the Customer class shouldn’t create an instance of DatabaseHelper, rather it should be received from the external system.

Dependency Injection is a way to implement IoC such that the dependencies are “injected” into a class from some external source. The injected dependencies can either be received as constructor parameters of a class or can be assigned to properties of that class designed for that purpose. The former approach is commonly used in ASP.NET MVC. So, the above code now becomes:

  1. public class Customer
  2. {
  3. private IStorageHelper helper;
  5. public Customer(IStorageHelper helper)
  6. {
  7. this.helper = helper;
  8. }
  9. }

As you can see, the helper instance is now coming from the external world and is being injected into the Customer class through its constructor.

Applying Dependency Injection in ASP.NET MVC

Now that you understand the basics of Dependency Injection, let’s see how DI can be used in ASP.NET MVC controllers. Consider the following controller class:

  1. public class HomeController : Controller
  2. {
  3. ICustomerRepository repository = null;
  5. public HomeController(ICustomerRepository repository)
  6. {
  7. this.repository = repository;
  8. }
  10. public ActionResult Index()
  11. {
  12. List<CustomerViewModel> data = repository.SelectAll();
  13. return View(data);
  14. }
  15. }

The above code should be immediately familiar to you because it uses the concept of IoC and DI as discussed in the previous section. The HomeController class declares a variable of ICustomerRepository. The ICustomerRepository is an interface designed to implement the Repository pattern and is shown below:

  1. public interface ICustomerRepository
  2. {
  3. List<CustomerViewModel> SelectAll();
  4. CustomerViewModel SelectByID(string id);
  5. void Insert(CustomerViewModel obj);
  6. void Update(CustomerViewModel obj);
  7. void Delete(CustomerViewModel obj);
  8. }

In the above code some implementation of ICustomerRepository is injected inside the HomeController through its constructor. As you can see the Index() action method calls the SelectAll() method on the repository to retrieve all the customers as a List of CustomerViewModel objects. The CustomerViewModel is a simple class that acts as a view model and is shown below:

  1. public class CustomerViewModel
  2. {
  3. public string CustomerID { get; set; }
  4. public string CompanyName { get; set; }
  5. public string ContactName { get; set; }
  6. public string Country { get; set; }
  7. }

Although the above code seems to apply DI as expected there is a problem. The problem is that while instantiating the HomeController for processing the incoming requests, ASP.NET MVC framework uses the parameter less constructor of the HomeController. Since our HomeController no longer has one, the above code throws an exception at runtime. Luckily, ASP.NET MVC allows you to explicitly specify how controllers should be instantiated. This can be done by creating your own Controller Factory.

A controller factory is a class that usually inherits from DefaultControllerFactory class and is responsible for creating controller instances. Once created you need to register your custom controller factory with the ASP.NET MVC framework so that it can use your controller factory instead of the default one. Let’s create the custom controller factory first. Have a look at the following code:

  1. public class MyControllerFactory:DefaultControllerFactory
  2. {
  3. private Dictionary<string, Func<RequestContext, IController>> controllers;
  5. public MyControllerFactory(ICustomerRepository repository)
  6. {
  7. controllers = new Dictionary<string, Func<RequestContext, IController>>();
  8. controllers[“Home”] = controller => new HomeController(repository);
  9. }
  11. public override IController CreateController(RequestContext requestContext, string controllerName)
  12. {
  13. if(controllers.ContainsKey(controllerName))
  14. {
  15. return controllers[controllerName](requestContext);
  16. }
  17. else
  18. {
  19. return null;
  20. }
  21. }
  22. }

The MyControllerFactory class inherits from the DefaultControllerFactory class provided by the ASP.NET MVC framework. The constructor of MyControllerFactory accepts an instance of ICustomerRepository. This way the MyControllerFactory doesn’t depend on any concrete implementation of ICustomerRepository. The code then overrides the CreateController() method of the base class. A Dictionary objects maintains a list of controllers in the application. Notice that HomeController is being instantiated in the constructor and is stored with a key of Home. The CreateController() simply returns this instance of HomeController from the Dictionary.

Now that the custom controller factory is ready, you need to register it with the ASP.NET MVC framework. To help you with this registration we create a helper class – ControllerFactoryHelper – as shown below:

  1. public class ControllerFactoryHelper
  2. {
  3. public static IControllerFactory GetControllerFactory()
  4. {
  5. string repositoryTypeName = ConfigurationManager.AppSettings[“repository”];
  6. var repositoryType = Type.GetType(repositoryTypeName);
  7. var repository = Activator.CreateInstance(repositoryType);
  8. IControllerFactory factory = new MyControllerFactory(repository as ICustomerRepository);
  9. return factory;
  10. }
  11. }

The ControllerFactoryHelper class has just one static method, GetControllerFactory(). The job of GetControllerFactory() is to instantiate MyControllerFactory and prepare for the registration. This is the place where the concrete implementation of ICustomerRepository are required. This is so because unless these details are known you can’t instantiate MyControllerFactory (since the constructor of MyControllerFactory needs an object implementing ICustomerRepository). The above code assumes that these details are stored in the <appSettings> section of the web.config file as shown below:

  1. <appSettings>
  2. <add key=“repository” value=“DIDemo.Repositories.CustomerRepository”/>
  3. </appSettings>

The GetControllerFactory() reads the repository key and creates an instance of DIDemo.Repositories.CustomerRepository using Reflection. It then instantiates MyControllerFactory by passing this object. The factory object is then returned to the caller.

Now comes the final step. To register the custom controller factory you need to add the following code in Globa.asax:

  1. protected void Application_Start()
  2. {
  3. AreaRegistration.RegisterAllAreas();
  4. RouteConfig.RegisterRoutes(RouteTable.Routes);
  6. ControllerBuilder.Current.SetControllerFactory(ControllerFactoryHelper.GetControllerFactory());
  7. }

The Application_Start event handler uses the ControllerBuilder instance and calls its SetControllerFactory() method. The factory object returned by the GetControllerFactory() static method is passed as a parameter to the SetControllerFactory() method.

That’s it! The following figure shows a sample run of the Index view.

Index View


Dependency Injection is a technique to separate the creation of dependencies from the main class under consideration. Using DI you inject the objects needed  by a class typically through a constructor. This article illustrated how DI can be used in ASP.NET MVC controllers. For the sake of simplicity it didn’t use any IoC Container frameworks such as Unity, Castle Windsor and NInject. In real world applications you may use one of such frameworks to make your job easier.