Search code examples
c#interfacecode-reuse

How to reference a class that implements certain interface?


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.


Solution

  • //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 
      }
    }