使用Simple Injector的RegisterCollection注册的实现不会被修饰

时间:2017-02-14 23:42:11

标签: c# simple-injector

我有一个构造函数(AnimalHandler),它接受同一个接口(IAnimal)的两个稍微不同的实现。使用Simple Injector,我如何自动装饰这两种实现?

一个例子的年代表:

interface IAnimal {
  string Speak();
}
class Cat : IAnimal{
  public string Speak() => "Meow";
}
class Dog : IAnimal{
  public string Speak() => "Woof";
}
class AnimalSpeakLoudlyDecorator : IAnimal {
  private readonly IAnimal _decorated;
  public AnimalSpeakLoudlyDecorator(IAnimal decorated) {
    _decorated = decorated;
  }
  public string Speak() => _decorated.Speak().ToUpper();
}
class AnimalHandler {
  private readonly Cat _cat;
  private readonly Dog _dog;
  public AnimalHandler(Cat cat, Dog dog) {
    _cat = cat;
    _dog = dog;
  }
  public string HandleCat() => _cat.Speak();
  public string HandleDog() => _dog.Speak();
}

这里我意识到应该在构造函数中使用接口,以便可以进行修饰。因此,我创建了AnimalInterfaceHandlerICatIDog

interface ICat : IAnimal { }
interface IDog : IAnimal { }
class Cat : ICat {...}
class Dog : IDog {...}
class AnimalInterfaceHandler {
  private readonly ICat _cat;
  private readonly IDog _dog;
  public AnimalInterfaceHandler(ICat cat, IDog dog) {
    _cat = cat;
    _dog = dog;
  }
  public string HandleCat() => _cat.Speak();
  public string HandleDog() => _dog.Speak();
}

register multiple interfaces with the same implementation

var container = new Container();
var catRegistration = Lifestyle.Singleton.CreateRegistration<Cat>(container);
container.AddRegistration(typeof(ICat), catRegistration);
var dogRegistration = Lifestyle.Singleton.CreateRegistration<Dog>(container);
container.AddRegistration(typeof(IDog), dogRegistration);
container.RegisterCollection<IAnimal>(new[] { catRegistration, dogRegistration });
container.RegisterDecorator(typeof(IAnimal), typeof(AnimalSpeakLoudlyDecorator), Lifestyle.Singleton);
container.Verify();
var handler = container.GetInstance<AnimalInterfaceHandler>();
Assert.AreEqual("MEOW", handler.HandleCat());

断言失败;尽管IAnimal已在RegisterCollection注册,但未应用装饰器。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

var container = new Container();

container.RegisterConditional<IAnimal, Cat>(c => c.Consumer.Target.Name == "cat");
container.RegisterConditional<IAnimal, Dog>(c => c.Consumer.Target.Name == "dog");

container.RegisterDecorator(typeof(IAnimal), typeof(AnimalSpeakLoudlyDecorator));

container.Verify();

此注册使用RegisterConditional方法,该方法允许根据有关消费者的信息进行条件或上下文注册。在这种情况下,它使用它注入的构造函数参数的名称。