mardi 7 juillet 2020

Dependency Injection of an asynchronously constructed Singleton

I've got myself in a bit of a tangle.

My WPF application depends on a few resources that take a little time to spin up, but once created, they can be cached and reused, so I decided to put them in a ServiceManager object that I create as a Singleton when the application starts.

A pattern suggested for creating such an Object was the Static Factory pattern i.e

public class ServiceManager
{
   protected ServiceManager ()

   public static async Task<IServiceManger> CreateAsync()
   {
     await SomeLongRunningMethodThatSetsPropertiesOnServiceManager()
     ...
     return this;
   }

   private async Task SomeLongRunningMethodThatSetsPropertiesOnServiceManager()
   {
    ....
   }

}

But having built this, I've realised this causes problems with DependencyInjection

So I'm thinking of scrapping the static factory and taking the long-running stuff OUT of the constructor and into a public Initialise() method, which I could call during the ApplicationStartup process.

public class ServiceManager : IServiceManager
{
    private bool _initialised;

    public ServiceManager 
    (
        _initialised = false;       
    )

    
    public async Task<IServiceManger> IniatialiseAsync()
    {
        if(!_initialised)
        {
          await SomeLongRunningMethodThatSetsPropertiesOnServiceManager()
                ...
          _initialise = true;
        }
    }

    private async Task SomeLongRunningMethodThatSetsPropertiesOnServiceManager()
    {
        ....
    }
}

and using this answer put the following in App.xaml.cs

  protected override async void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            _iocKernel = new StandardKernel();
            _iocKernel.Load(new ServiceManager());
    }

and put the IniatialiseAsync() call in the OnLoad event of MainWindow.xaml

Is this a good approach - or is there a better way of designing this? Apologies but after a 7 year break from coding, I'm having to feel my way back quite slowly.

Aucun commentaire:

Enregistrer un commentaire