简单注入器-注册IEnumerable抽象类实现

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进行处理,因为在此子类中还使用了其他注册(不是在这种情况下,而是在实际示例中)。

注意:如果有其他方法的想法,也欢迎您!

Ste*_*ven 5

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)

  • @AliKareemRaja 手动新建实例不是问题,只要这发生在组合根内部并且不损害可维护性。此外,这些示例中唯一的新语句是创建周围的 Type 和 Assembly 数组,而不是创建应用程序组件。 (2认同)