I have a classes tree having one being inheriting the other. All these base classes have different types of functionalities. So the inheriting class can choose which one to go for. Functionalities are move from base class to upwards. The base functionality of these classes requires IServiceProvider
to be resolved.
The first solution which I don't like is passing IServiceProvider
into the handler class which moves from one base to the next and so on.
The second one is what I am looking for. I looking for a workaround that I should be able to create instances of my handler classes without parameters and the base class itself should resolve IServiceProvider
whenever required.
I could not find a solution to this till now.
Code example to make the question meaningful I am adding some code skeleton.
abstract class Root<ResultType, DbClass>
where ResultType : class
where DbClass : class
{
private DbContext ent;
abstract ResultType DefineHowToCreateResult(DbClass inputClass);
IEnumerable<ResultType> GetAll()
{
// This class itself should be able to resolve the context. So everytime
// it should not expect it to come all the way from child
ent = ResolveContext<DbContext>();
return DefineHowToCreateResult(ent.DbClass());
}
DbClass AddNew(DbClass inputPara)
{
// This class itself should be able to resolve the context. So everytime
// it should not expect it to come all the way from child
ent = ResolveContext<DbContext>();
ent.AddNew(inputPara);
return DbClass;
}
}
Some functionalities come under the scope of this intermediate class. But it is never supposed to do GetAll()
or AddNew()
kind of functionalities. Because it is supposed to be handled by the Root class.
abstract class IntermediatRoot<ResultType, DbClass, InterMediatPara>
: Root<ResultType, DbClass>
where ResultType : class
where DbClass : class
where InterMediatPara : class
{
ResultType PerformInterMediatWork()
{
var allData = GetAll();
//------
//------
//------
//------
//------
return ResultType;
}
}
I simply want it to be a parameterless constructor and don't want to take IServiceProvider
all the way down. Because ultimately it is required on Root class and I want that root class to be able to resolve the perform what I want. It would make that class a little bit independent and self-responsible for the scope of work given to it.
internal class HandlerClass : IntermediatRoot<H1, H2, H3>
{
private override H1 DefineHowToCreateResult(H2 inputClass)
{
//------
//------
//------
//------
}
}
class H1 { }
class H2 { }
class H3 { }