sTo*_*rov 4 c# dependency-injection simple-injector
我正在使用Simple Injector,希望查看是否可以注册/解析继承抽象类的类的集合。
情况如下:我具有以下抽象/具体类:
public abstract class Animal
{
public string Type { get; set; }
public abstract string MakeSound();
}
public class Dog : Animal
{
public override string MakeSound()
{
return "woof";
}
}
public class Cat : Animal
{
public override string MakeSound()
{
return "meow";
}
}
public class Pig : Animal
{
public override string MakeSound()
{
return "oink";
}
}
Run Code Online (Sandbox Code Playgroud)
此外,我有一个应接收an的类,IEnumerable<Animal>并MakeSound为每个动物调用该函数,如下所示:
public class Zoo
{
private IEnumerable<Animal> _animals;
public Zoo(IEnumerable<Animal> animals)
{
_animals = animals;
}
public void MakeZooNoise()
{
foreach (var animal in _animals)
{
animal.MakeSound();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想IEnumerable<Animal>最好使用Container初始化来构建集合,并使其通过Simple Injector进行处理,因为在此子类中还使用了其他注册(不是在这种情况下,而是在实际示例中)。
注意:如果有其他方法的想法,也欢迎您!
container.RegisterCollection<Animal>(new[] {
typeof(Cat),
typeof(Dog),
typeof(Pig)
});
// or using Auto-Registration
container.RegisterCollection<Animal>(new [] {
typeof(Animal).Assembly
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1121 次 |
| 最近记录: |