简体   繁体   中英

LightInject - Register multiple implementation of same interface

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM