Search code examples
c#.net-coreabp-framework

Is there any way to use AddSingleton in ApplicationInitialization under the ABP framework?


I'm using the ABP framework, and want to register a singleton class for global use. but it needs some other class. So I want the OnApplicationInitialization function to register it.

 public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
     var settingManager = context.ServiceProvider.GetService<ISettingManager>();
     var cloudStorageProviderManager = context.ServiceProvider.GetService<ISlideCloudStorageProviderManager>();
      var cloudProvider = await settingManager.GetOrNullGlobalAsync(CloudStorageSettings.CloudProvider);
      var slideCloudStorage = cloudStorageProviderManager.Resolve(cloudProvider);

      // how to  register slideCloudStorage.
}

Solution

  • This seems to be an XY Problem.

    Is there any way to register a singleton class that needs some other class? (Problem X)

    Yes, you can use AddSingleton in ConfigureServices with a function as an implementation factory.

    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        context.Services.AddSingleton(serviceProvider =>
        {
            var settingManager = serviceProvider.GetService<ISettingManager>();
            var cloudStorageProviderManager = serviceProvider.GetService<ISlideCloudStorageProviderManager>();
            var cloudProvider = settingManager.GetOrNullGlobal(CloudStorageSettings.CloudProvider);
            return cloudStorageProviderManager.Resolve(cloudProvider);
        });
    }
    

    Is there any way to use AddSingleton in ApplicationInitialization under ABP framework? (Solution Y)

    No, there is no supported way.