0

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.

Eutherpy
  • 4,471
  • 7
  • 40
  • 64
  • 2
    Composing object graphs is (and always should be) a synchronous operation. There is no DI Container that can compose object graphs asynchronously for you, and so can't MS.DI. This is (IMO) actually a good thing, because [injection constructors should be simple](https://blog.ploeh.dk/2011/03/03/InjectionConstructorsshouldbesimple/) and object graph composition should be reliable. You will have to design with this accordingly. One way is to keep runtime data (like `MyClass`) [out of your constructors](https://blogs.cuttingedge.it/steven/p/runtime-data/). – Steven Apr 15 '20 at 12:56
  • 3
    Does this answer your question? [async provider in .net core DI](https://stackoverflow.com/questions/43240405/async-provider-in-net-core-di) – Johnathan Barclay Apr 15 '20 at 12:57

0 Answers0