I have a parent-child class structure where parent class in constructor creates instance of the child class and use one of child class async methods with .Result approach.
public class ParentClass { private readonly ChildClass _childClass; public ParentClass() { _childClass = new ChildClass(); bool result = _childClass.GetSomething().Result; } } public class ChildClass { public ChildClass() { } public async Task<bool> GetSomething() { return await Task.FromResult<bool>(false); } }
My goal is to remove .Result and change it with normal await keyword. I can create static async method, there create instance of the child class, later call constructor and pass instance.
public class ParentClass2
{
private readonly ChildClass _childClass;
private ParentClass2(ChildClass childClass, bool result)
{
_childClass = childClass;
}
public static async Task<ParentClass2> GetInstance()
{
ChildClass childClass = new ChildClass();
bool result = await childClass.GetSomething();
return new ParentClass2(childClass, result);
}
}
But then I have 2 problems:
The more parents of parents [..of parents] I have - the more code I have to modify in a same way.
Highest level classes use DI. And with async I can't do this
services.AddScoped<ParentClass2>(async p => { var instance = await ParentClass2.GetInstance(); return instance; });
Any suggestions?