How to refer to a class that implements a specific interface?

I have an interface for registering exceptions, i.e. IExceptionLogger.

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

I have an application that will use DBExceptionLogger.

The application refers only to IExceptionLogger. How to create an instance DBExceptionLoggerin the application.

I cannot reference DBExceptionLoggerdirectly, as this would violate the goal of having an interface IExceptionLogger.

+3
source share
5 answers
//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 
  }
}
+3
source

. , , , . , .NET: Unity, Spring.NET, Autofac, LinFu, .

+7

Factory (, IExceptionLogger) , , .

+3
IExceptionLogger logger = new DBExceptionLogger();

logger , .

+2

Bad Man DI factory :

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

Source: https://habr.com/ru/post/1749181/


All Articles