Reputation: 4665
I have 1 abstract class that is used by 2 other classes inheriting from it:
public abstract class FiltererBase
{
ColorsOrderer colorsOrderer;
public FiltererBase(ColorsOrderer colorsOrderer)
{
this.colorsOrderer = colorsOrderer;
}
protected string OrderColors(string colors)
{
return string.Join("", colors.ToCharArray().OrderBy(i => colorsOrderer.Order[i]));
}
}
public class Filterer1 : FiltererBase
{
public Filterer1(ColorsOrderer colorsOrderer)
: base(colorsOrderer) { }
}
public class Filterer2 : FiltererBase
{
public Filterer2(ColorsOrderer colorsOrderer)
: base(colorsOrderer) { }
}
As you can see, I am using dependency injection (DI) and passing the class instantiated from the child constructor to the parent constructor.
Is it really the best way to do DI with abstract (base) classes? Isn't the .NET Core framework providing a more automatic way to do that?
Upvotes: 0
Views: 1067
Reputation: 68
Unfortunately, it's not possible to inject parameters into a parent constructor.
You could use a composition approach instead of inheritance.
Refactoring your code to a composition approach, it would appear like this:
public class ColorFilter
{
ColorsOrderer colorsOrderer;
public ColorFilter(ColorsOrderer colorsOrderer)
{
this.colorsOrderer = colorsOrderer;
}
public string OrderColors(string colors)
{
return string.Join("", colors.ToCharArray().OrderBy(i => colorsOrderer.Order[i]));
}
}
public class Filterer1
{
ColorFilter colorFilter;
public Filterer1(ColorFilter colorFilter)
{
this.colorFilter = colorFilter;
}
public string OrderColors(string colors)
{
return this.colorFilter(colors);
}
}
public class Filterer2
{
ColorFilter colorFilter;
public Filterer2(ColorFilter colorFilter)
{
this.colorFilter = colorFilter;
}
public string OrderColors(string colors)
{
return this.colorFilter(colors);
}
}
Upvotes: 1