Dependency Injection and Lazy Loading

When using dependency injection you might get to a point where you need to supply a dependency on something that is expensive to create, for example:

A database connection
An object that takes long to create.
This would be fine if you were definitely using the dependency, but there are scenarios where the dependency might just sometimes be used.

Even though you can inject an abstract factory or a lambda function to evaluate the dependency, this didn’t feel so nice. And also felt like extra effort to define and also to manage the instance variable.

But it turns out that this problem can be solved elegantly in .NET 4 with a new class called:

Lazy

Lazy solves this problem in 2 ways:
Lazy load the instance by automatically activating only when used.
Takes care of recycling the same instance variable.

Below is the Code sample

 

public interface ILogger
{
    void Log();
}
 
public class FileLogger : ILogger
{
    public FileLogger()
    {
        Console.WriteLine("Inside File Logger Constructor");
    }
    public void Log()
    {
        Console.WriteLine("In File Logger Log Method..");
    }
}
 
public class Customer
{
    Lazy<ILogger> logger;
 
    public Customer()
    {
        this.logger = new Lazy<ILogger>();
    }
 
    public Customer(Lazy<ILogger> log)
    {
        Console.WriteLine("Inside Customer Constructor");
        this.logger = log;
    }
 
    public void PlaceOrder()
    {
        try
        {
            Console.WriteLine("Iniside Place Order");
            this.logger.Value.Log();
        }
        catch
        {
            this.logger.Value.Log();
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Instantiating Lazy<ILogger>");
        Lazy<ILogger> logger = new Lazy<ILogger>(() => { return new FileLogger(); });
        Customer cust = new Customer(logger);
        cust.PlaceOrder();
        Console.ReadLine();
    }
}

Attached is the source code Here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s