Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 402
awashima Avatar asked Nov 19 '25 04:11

awashima


1 Answers

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);
....
like image 58
B.Ramburn Avatar answered Nov 21 '25 17:11

B.Ramburn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!