使用Lightinjector DI框架如何注册同一接口的多个实现?如何在构造函数上提到相同的接口并要求其不同的实现?
container.Register<IInterface1, Myclass1>();
container.Register<IInterface1, Myclass2>();
尝试Annotation时,遇到以下异常
"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 3901rn at LightInject.ServiceContainer.CreateDefaultDelegate(Type serviceType, Boolean throwError) in C:\projects\lightinject\build\tmp\netstandard16\Binary\LightInject\LightInject.cs:line 3859rn at LightInject.ServiceContainer.TryGetInstance(Type serviceType) in C:\projects\lightinject\build\tmp\netstandard16\Binary\LightInject\LightInject.cs:line 2777rn at LightInject.Scope.WithThisScope[T](Func`1 function) in C:\projects\lightinject\build\tmp\netstandard16\Binary\LightInject\LightInject.cs:line 6169rn
集装箱登记如下,
container.EnableAnnotatedPropertyInjection();
container.Register<ILoginHandler, LoginHandler>("LoginHandler");
类上的构造函数注入";用户.cs";如下所示,
public class User
{
public ILoginHandler _loginHandler { get; private set; }
public class([Inject(serviceName: "LoginHandler")]ILoginHandler loginHandler)
{
_loginHandler = loginHandler;
}
}
这被称为命名服务,这在我见过的大多数IOC/DI容器中都是非常标准的(请参阅命名服务部分(。
container.Register<IInterface1, Myclass1>("Foo");
container.Register<IInterface1, Myclass2>("Bar");
var instance = container.GetInstance<IInterface1>("Foo");
Assert.IsInstanceOfType(instance, typeof(Myclass1));
有道理吗?:(
public class FooWithNamedAnnotatedProperyDependency
{
[Inject("Foo")]
public IInterface1 Service { get; set; }
}
或
public FooWithNamedAnnotatedDependency([Inject(ServiceName="Foo")]IInterface1 service)
{
_service = service;
}
查看注释