views:

87

answers:

5

I have an interface for logging the exceptions, i.e. IExceptionLogger.

This interface has 3 implementations: DBExceptionLogger, XMLExceptionLogger, CSVExceptionLogger.

I have an application that will make a use of DBExceptionLogger.

The application references only IExceptionLogger. How do I create an instance of DBExceptionLogger within the application.

I can't reference the DBExceptionLogger directly since it will break the purpose of having IExceptionLogger interface.

+7  A: 

You should look at the concepts of inversion of control and dependency injection. These will help you to inject a particular instance of an object that implements your interface, with your code needing to be aware of exactly what it is beyond that fact. There are many libraries to help you in .NET: Unity, Spring.NET, Autofac, LinFu to name but a few.

David M
Is this the only way of doing this? Ideally I don't want to use any non .Net libraries.
vikp
The ones I have mentioned are all .NET libraries.
David M
+3  A: 

You can use the Factory pattern (a class whose responsibility is creating an IExceptionLogger class), or more generally, an Inversion of Control framework.

Stephen Cleary
+2  A: 
IExceptionLogger logger = new DBExceptionLogger();

then pass logger variable to all your classes which write logging information.

Arseny
+1  A: 

Hi, you can use Poor Man's DI with a static factory like this:

public class ExceptionLoggerFactory
{
    public static IExceptionLogger GetDBLogger()
    {
        return new DBExceptionLogger();
    }
}

public class MyClass
{
    private IExceptionLogger _logger;

    public MyClass() : this(ExceptionLoggerFactory.GetDBLogger())
    {

    }

    public MyClass(IExceptionLogger logger)
    {
        _logger = logger;
    }
}
Adrian Magdas
+2  A: 
//Usage of logger with factory
IExceptionLogger logger = ExceptionLoggerFactory.GetLogger();

public static class ExceptionLoggerFactory
{
  public static IExceptionLogger GetLogger()
  {
    //logic to choose between the different exception loggers
    //e.g.
    if (someCondition)
      return new DBExceptionLogger();
    //else etc etc 
  }
}
Binoj Antony
Found few articles on factory pattern. Will implement one of my own this afternoon and use suggested code. Thx!
vikp