Take this simple example of abstraction, whereby the abstract class has implementation for common logic whereas the dervied classes have overrides for the abstract methods.
public abstract class Animal {
public abstract void Sound();
public void Sleep() {
Console.WriteLine("Zzz");
}
}
public class Cat : Animal {
public override void Sound() {
Console.WriteLine("Meow");
}
}
public class Dog : Animal {
public override void Sound() {
Console.WriteLine("Woof");
}
}
In order to use one of the dervied classes:
Cat cat = new Cat();
cat.Sound(); // Overriden logic
cat.Sleep(); // Common logic
My question is how would this translate when using dependency injection. In this I know how to register dependencies and pass them into a class via constructor injection. However what confuses me, is that DP uses interfaces to decouple the implementation. Obviously this is not the case for the above example, so in order to be able to inject either of the derived classes would it be as simple as the base class inheriting from a interface that would look something like this:
public interface IAnimal {
void Sound()'
void Sleep();
}
Is there anything wrong with this approach, as it provides access to common logic while still enabling unqiue behaviour? Is there any better solutions or design patterns that could be used when using dependency injection for when two classes share common logic but require their own implementation for specfic methods.
very obvious but why dont you make the abstract class inherit an interface ? And then in DP you can pass register whichever child class you want for that interface as usual.