gpt4 book ai didi

c# - 使用 Simple Injector 的 RegisterCollection 注册的实现没有被修饰

转载 作者:行者123 更新时间:2023-11-30 17:34:35 26 4
gpt4 key购买 nike

我有一个构造函数 (AnimalHandler),它采用同一接口(interface) (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();
}

在这里,我意识到应该在构造函数中使用接口(interface),以便进行装饰。因此,我创建了 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 中注册,但装饰器并未应用。有什么想法吗?

最佳答案

这应该可以解决问题:

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 方法,该方法允许根据有关消费者的信息进行条件或上下文注册。在这种情况下,它使用注入(inject)它的构造函数参数的名称。

关于c# - 使用 Simple Injector 的 RegisterCollection 注册的实现没有被修饰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42238270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com