I have some data that I need to load asynchronously in my class. Since I cannot have an async
constructor, I have tried to implement the factory pattern like this:
public class MyClass
{
private string someData;
private readonly IMyDependency md;
public MyClass(IMyDependency md)
{
this.md = md;
}
public async Task<MyClass> MyClassFactory()
{
string data = await LoadData();
return new MyClass(data);
}
private MyClass(string data) { someData = data; }
private async Task<string> LoadData()
{
await md.GetSomeData();
}
}
I understand that formally, the factory pattern assumes that my MyClassFactory()
is static
and that I call it explicitly to create MyClass
objects.
My problems with this are the following:
Firstly, MyClass
is a dependency for other modules and I am using ASP.NET Core's DI to inject it where it's necessary. This means that I never explicitly create objects of this class, the DI framework does it.
Secondly, I have this MyDependency
which I need to inject into MyClass
and I'm using it in the LoadData() method, which would prevent the LoadData()
, and consequently the MyClassFactory()
to be static
.