使用 serviceKey 解决 DryIoc 中的子依赖失败
Resolving sub-dependency in DryIoc with a serviceKey fails
我想使用 serviceKey 来区分服务的不同实现。
代码解释:有个ICat接口,用来"say"一只猫的话"Meow"。 "Meow" 这个词来自 ISoundProducer 的实现(它被注入到 ICat 的实现中)。
我用相同的 serviceKey = "x" 注册了两个服务(ICat 和 ISoundProducer)。之后我尝试解析一个 ICat 实例,但它失败了。
这里是演示代码:
using DryIoc;
using System;
class Program
{
static void Main(string[] args)
{
Container ioc = new Container();
ioc.Register<ISoundProducer, GoodCatSoundProducer>(serviceKey: "x");
ioc.Register<ICat, GoodCat>(serviceKey: "x");
var c1 = ioc.Resolve<ICat>("x");
c1.Say();
Console.ReadKey();
}
}
public interface ISoundProducer
{
string ProduceSound();
}
public class GoodCatSoundProducer : ISoundProducer
{
string ISoundProducer.ProduceSound() => "Meow";
}
public interface ICat
{
void Say();
}
public class GoodCat : ICat
{
private ISoundProducer _soundProducer;
public GoodCat(ISoundProducer soundProducer) => this._soundProducer = soundProducer;
void ICat.Say() => Console.WriteLine(_soundProducer.ProduceSound());
}
这给了我一个例外:
Unable to resolve ISoundProducer as parameter "soundProducer" in
GoodCat: ICat {ServiceKey="x"} from container with normal and
dynamic registrations: x, {ID=28, ImplType=GoodCatSoundProducer}}
我做错了什么?我怎样才能用另一个注入的服务解析一个服务,而它们都具有相同的 serviceKey?
指定依赖键:
ioc.Register<ICat, GoodCat>(serviceKey: "x",
made: Made.Of(Parameters.Of.Type<ISoundProducer>(serviceKey: "x")));
ioc.Register<ISoundProducer, GoodCatSoundProducer>(serviceKey: "x");
我想使用 serviceKey 来区分服务的不同实现。
代码解释:有个ICat接口,用来"say"一只猫的话"Meow"。 "Meow" 这个词来自 ISoundProducer 的实现(它被注入到 ICat 的实现中)。
我用相同的 serviceKey = "x" 注册了两个服务(ICat 和 ISoundProducer)。之后我尝试解析一个 ICat 实例,但它失败了。
这里是演示代码:
using DryIoc;
using System;
class Program
{
static void Main(string[] args)
{
Container ioc = new Container();
ioc.Register<ISoundProducer, GoodCatSoundProducer>(serviceKey: "x");
ioc.Register<ICat, GoodCat>(serviceKey: "x");
var c1 = ioc.Resolve<ICat>("x");
c1.Say();
Console.ReadKey();
}
}
public interface ISoundProducer
{
string ProduceSound();
}
public class GoodCatSoundProducer : ISoundProducer
{
string ISoundProducer.ProduceSound() => "Meow";
}
public interface ICat
{
void Say();
}
public class GoodCat : ICat
{
private ISoundProducer _soundProducer;
public GoodCat(ISoundProducer soundProducer) => this._soundProducer = soundProducer;
void ICat.Say() => Console.WriteLine(_soundProducer.ProduceSound());
}
这给了我一个例外:
Unable to resolve ISoundProducer as parameter "soundProducer" in GoodCat: ICat {ServiceKey="x"} from container with normal and dynamic registrations: x, {ID=28, ImplType=GoodCatSoundProducer}}
我做错了什么?我怎样才能用另一个注入的服务解析一个服务,而它们都具有相同的 serviceKey?
指定依赖键:
ioc.Register<ICat, GoodCat>(serviceKey: "x",
made: Made.Of(Parameters.Of.Type<ISoundProducer>(serviceKey: "x")));
ioc.Register<ISoundProducer, GoodCatSoundProducer>(serviceKey: "x");