LightInject - Register multiple implementation of same interface

605 Views Asked by At

Using Lightinjector DI framework how to register multiple implementation of same interface? how to mention the same interface on constructor and ask for its different implementation?

     container.Register<IInterface1, Myclass1>();
     container.Register<IInterface1, Myclass2>();   

While trying Annotation, encountered below exception

 "message": "Unable to resolve type: 
    "innererror": {
      "trace": "   at LightInject.ServiceContainer.CreateDelegate(Type serviceType, String serviceName, Boolean throwError) in C:\\projects\\lightinject\\build\\tmp\\netstandard16\\Binary\\LightInject\\LightInject.cs:line 3901\r\n   at LightInject.ServiceContainer.CreateDefaultDelegate(Type serviceType, Boolean throwError) in C:\\projects\\lightinject\\build\\tmp\\netstandard16\\Binary\\LightInject\\LightInject.cs:line 3859\r\n   at LightInject.ServiceContainer.TryGetInstance(Type serviceType) in C:\\projects\\lightinject\\build\\tmp\\netstandard16\\Binary\\LightInject\\LightInject.cs:line 2777\r\n   at LightInject.Scope.WithThisScope[T](Func`1 function) in C:\\projects\\lightinject\\build\\tmp\\netstandard16\\Binary\\LightInject\\LightInject.cs:line 6169\r\n

Container registration as below,

     container.EnableAnnotatedPropertyInjection();
     container.Register<ILoginHandler, LoginHandler>("LoginHandler");

Constructor injection on class "User.cs" as below,

public class User
{
   public ILoginHandler _loginHandler { get; private  set; }    
   public class([Inject(serviceName: "LoginHandler")]ILoginHandler loginHandler)
   {
      _loginHandler = loginHandler;
   }
}
1

There are 1 best solutions below

8
On

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

 container.Register<IInterface1, Myclass1>("Foo");
 container.Register<IInterface1, Myclass2>("Bar");
 var instance = container.GetInstance<IInterface1>("Foo");
 Assert.IsInstanceOfType(instance, typeof(Myclass1));

Makes sense? :)

 public class FooWithNamedAnnotatedProperyDependency
{
    [Inject("Foo")]
    public IInterface1 Service { get; set; }
}

or

public FooWithNamedAnnotatedDependency([Inject(ServiceName="Foo")]IInterface1 service)
{
    _service = service;
}

look at annotations