简体   繁体   中英

How to DI register FirebaseApp in .Net Core?

How should I register FirebaseApp instance in Net core? As a singleton like

   //startup.cs
   services.AddSingleton<FirebaseApp>(sp =>
   {
       FirebaseApp.Create(new AppOptions
       {
           Credential = GoogleCredential.FromJson(settings)
       });
   });

Or as scoped similarly

   //startup.cs
   services.AddScoped<FirebaseApp>(sp =>
   {
       FirebaseApp.Create(new AppOptions
       {
           Credential = GoogleCredential.FromJson(settings)
       });
   });

Or some third option?

So right after the builder in .net 6 I just instantiate it using the following:

var builder = WebApplication.CreateBuilder(args);
// after the builder so that I can get the configurations for google credentials
// check if the instance is already loaded, if not build it up
if(FirebaseApp.DefaultInstance == null)
{
    FirebaseApp.Create(new AppOptions()
    {
        Credential = GoogleCredential.FromJson(AuthConfig.GetGoogleCredentialObject(builder.Configuration).ToString())
    });
}

Then, you don't need to inject it into the constructor of your classes.

You just call up the instance and load up the other firebase modules like so:

...
// this is a singleton and the props are static so available anytime
var customToken = FirebaseApp.DefaultInstance;

// use the instance from the singleton
await FirebaseAuth.GetAuth(customToken).SetCustomUserClaimsAsync(uid, additionalClaims);
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM