C
C#3y ago
ross

Multiple classes defining same props vs inherit from base class

Say I have multiple service classes, here's two as an example:
public class FooService {

private readonly DbContext _db;
private readonly ILogger<FooService> _logger;

public FooService(DbContext db, ILogger<FooService> logger) {
_db = db;
_logger = logger;
}
}

public class BarService {

private readonly DbContext _db;
private readonly ILogger<FooService> _logger;

public BarService(DbContext db, ILogger<BarService> logger) {
_db = db;
_logger = logger;
}
}
public class FooService {

private readonly DbContext _db;
private readonly ILogger<FooService> _logger;

public FooService(DbContext db, ILogger<FooService> logger) {
_db = db;
_logger = logger;
}
}

public class BarService {

private readonly DbContext _db;
private readonly ILogger<FooService> _logger;

public BarService(DbContext db, ILogger<BarService> logger) {
_db = db;
_logger = logger;
}
}
Instead of repeating the two private properties and the ctor on every service class, would it be acceptable to create a base class which the service classes inherit from? E.g:
public class BaseService {

public readonly DbContext _db;
public readonly ILogger<BaseService> _logger;

public BaseService(DbContext db, ILogger<BaseService> logger) {
_db = db;
_logger = logger;
}
}

public class FooService {

public FooService(DbContext db, ILogger<BaseService> logger) : base(db, logger)
{
}
}

public class BarService{

public BarService(DbContext db, ILogger<BaseService> logger) : base(db, logger)
{
}
}
public class BaseService {

public readonly DbContext _db;
public readonly ILogger<BaseService> _logger;

public BaseService(DbContext db, ILogger<BaseService> logger) {
_db = db;
_logger = logger;
}
}

public class FooService {

public FooService(DbContext db, ILogger<BaseService> logger) : base(db, logger)
{
}
}

public class BarService{

public BarService(DbContext db, ILogger<BaseService> logger) : base(db, logger)
{
}
}
I'm just approaching this from a DRY point of view. Technically I'm still repeating myself with the ctor in every service class, but it just seems cleaner? Some guidance would be much appreciated
5 Replies
ero
ero3y ago
in any case, make sure the base class is abstract
Cisien
Cisien3y ago
you can make the properties protected if they aren't intended for use outside of the inherited types
ross
rossOP3y ago
So what I'm gathering is that it's an acceptable way to go, just need to tweak a couple of things?
Cisien
Cisien3y ago
yes
ross
rossOP3y ago
Thanks fellas
Want results from more Discord servers?
Add your server