Reputation: 1761
I want to use a serviceKey to distinguish between different implementations of a service.
Code explanation: there is an ICat interface, which is used to "say" a cat's word "Meow". The word "Meow" comes from the implementation of ISoundProducer (it is injected into an implementation of ICat).
I register two services (ICat and ISoundProducer) with the same serviceKey = "x". After that I try to resolve an ICat instance, but it fails.
Here is the demo code:
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());
}
This gives me an exception:
Unable to resolve ISoundProducer as parameter "soundProducer" in GoodCat: ICat {ServiceKey="x"} from container with normal and dynamic registrations: x, {ID=28, ImplType=GoodCatSoundProducer}}
What am I doing wrong? How can I resolve a service with another injected service, while they both have the same serviceKey?
Upvotes: 1
Views: 766
Reputation: 4950
Specify the key of dependency:
ioc.Register<ICat, GoodCat>(serviceKey: "x",
made: Made.Of(Parameters.Of.Type<ISoundProducer>(serviceKey: "x")));
ioc.Register<ISoundProducer, GoodCatSoundProducer>(serviceKey: "x");
Upvotes: 3