user338195
user338195

Reputation:

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.

Upvotes: 3

Views: 192

Answers (5)

Binoj Antony
Binoj Antony

Reputation: 16196

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

Upvotes: 3

Adrian Magdas
Adrian Magdas

Reputation: 613

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;
    }
}

Upvotes: 1

Arseny
Arseny

Reputation: 7351

IExceptionLogger logger = new DBExceptionLogger();

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

Upvotes: 2

Stephen Cleary
Stephen Cleary

Reputation: 456437

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

Upvotes: 3

David M
David M

Reputation: 72860

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.

Upvotes: 7

Related Questions