ioc-containerlight-inject

Register Multiple Interface Implementation In LightInject IoC


I have an interface with two implementations.

public interface ILogger
{
   void Log(string message);
}

public class FileLogger : ILogger
{
   public void Log(string message) {}
}

public class SQLiteLogger : ILogger
{
  public void Log(string message) {}
}

I try using this code, but doesn't work.

ServiceContainer service = new ServiceContainer();
service.Register<ILogger, FileLogger>();
service.Register<ILogger, SQLiteLogger>();

LightInject will omit the first registration and only register SQLiteLogger. So how to register same interface with multiple implementation in LightInject ?


Solution

  • This is called Named Services - which is quite standard across most IOC/DI containers that I've seen (see section on named services).

    The documentation provides all the detail you need but here is a cut-and-paste from their website:

    container.Register<IFoo, Foo>();
    container.Register<IFoo, AnotherFoo>("AnotherFoo");
    var instance = container.GetInstance<IFoo>("AnotherFoo");
    Assert.IsInstanceOfType(instance, typeof(AnotherFoo));