.NET Core 中抽象 class 的依赖注入

Dependency injection with abstract class in .NET Core

我不知道如何在摘要中使用依赖注入 class。让我用一个简单的例子向您展示我的问题:

public abstract class Animal {

    public abstract void Move();

    public void Sleep() 
    {
        restService.StartSleeping(1000);    //how to get this service here?
    }
}

public class Cat : Animal
{
    public readonly IMotionService _motionService;    

    public Cat(IMotionService motionService)
    {
       _motionService = motionService;
    }

    public override void Move()
    {
        _motionService.Run();
    }
}

public class Bird : Animal
{
    public readonly IMotionService _motionService;    

    public Bird(IMotionService motionService)
    {
       _motionService = motionService;
    }

    public override void Move()
    {
        _motionService.Fly();
    }
}

每种动物的移动方式都不同,因此 Move() 函数在每个派生的 class 中分别实现。正如您可能注意到的那样,整个实现来自 motionService。 另一方面,所有动物都以相同的方式睡觉,所以我想将 Sleep() 实现放在基础抽象 class 中以避免重复代码,但我不能将我的 restServiceSleep 实现,因为我不知道如何将服务 class 注入抽象 class。

想过IServiceProvider不过应该也注入吧

你这样传下去:

public abstract class Animal 
{
    private readonly IRestService restService;

    public Animal( IRestService restService )
    {
        this.restService = restService;
    }

    public abstract void Move();

    public void Sleep() 
    {
        restService.StartSleeping(1000);
    }
}

public class Cat : Animal
{
    // vv Should be private!
    public readonly IMotionService _motionService;    

    public Cat(IMotionService motionService, 
               IRestService restService)
            : base(restService) // pass on to base class ctor
    {
       _motionService = motionService;
    }

    public override void Move()
    {
        _motionService.Run();
    }
}

// Same in `Bird` class

供参考:Using Constructors (C# Programming Guide)