Got The default FirebaseApp already exists
Asked Answered
M

7

7

I make an C# API to push notification to Flutter app.

My API basically like code below :

public async Task < IActionResult > pushNotification () {
  FirebaseApp.Create(new AppOptions() {
    Credential = GoogleCredential.FromFile("file.json")
  });
  .....
} 

I past url "domain.com/api/controller/pushNotification" on my browser, the first time it's work. My flutter receive notification perfectly. But the second time I got :

System.ArgumentException: The default FirebaseApp already exists.
   at FirebaseAdmin.FirebaseApp.Create(AppOptions options, String name)
   at FirebaseAdmin.FirebaseApp.Create(AppOptions options)

Why ? And how can I fix that ?

Mauricio answered 20/9, 2021 at 21:28 Comment(0)
R
16

You can simply check whether there is or isn't a FirebaseApp Instance by

if (FirebaseApp.DefaultInstance == null)
    {
        App = FirebaseApp.Create(new AppOptions()
        {
            Credential = GoogleCredential.FromFile("file.json")
        });
    }
Ruthi answered 4/11, 2021 at 14:34 Comment(0)
S
4

Carset answer took me really close to what I needed.

I just changed my constructor to look this way and worked perfect

public MobileMessagingClient()
    {
        var app = FirebaseApp.DefaultInstance;
        if (FirebaseApp.DefaultInstance == null)
        {
            app = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile(HttpContext.Current.Server.MapPath("~/file.json"))
            .CreateScoped("https://www.googleapis.com/auth/firebase.messaging")
            });
        }            
        messaging = FirebaseMessaging.GetMessaging(app);
    }
Schumann answered 9/8, 2022 at 17:12 Comment(0)
E
2

the first time it's work. My flutter receive notification perfectly. But the second time I got

Your error message is saying that you're trying to initialize an app that already exists.

To fix this, you need to first check if the app has been initialized. Before running your piece of code that initializes the Firebase app, add a simple check, for example:

public async Task < IActionResult > pushNotification () {
if(appDoesNotExistYet) {
  FirebaseApp.Create(new AppOptions() {
    Credential = GoogleCredential.FromFile("file.json")
  });
}

  .....
} 
Echoechoic answered 20/9, 2021 at 22:54 Comment(0)
Y
1

Firebase manages its own client internally, you can reference it by calling methods for Firebase which make a request to the defined or default "App" since you can technically have multiple Apps.

You most likely only want to initiate the Firebase App only if one does not already exist. I believe you can do this by checking the FirebaseApp.apps length - you should

Your answered 20/9, 2021 at 22:54 Comment(0)
P
0

If you use the default constructor without name it creates the default instance.

    /// <summary>Creates an app with the specified name and options.</summary>
    /// <returns>The newly created <see cref="T:FirebaseAdmin.FirebaseApp" /> instance.</returns>
    /// <exception cref="T:System.ArgumentException">If the default app instance already
    /// exists.</exception>
    /// <param name="options">Options to create the app with. Must at least contain the
    /// <c>Credential</c>.</param>
    /// <param name="name">Name of the app.</param>
    public static FirebaseApp Create(AppOptions options, string name)
    {
      if (string.IsNullOrEmpty(name))
        throw new ArgumentException("App name must not be null or empty");
      options = options ?? FirebaseApp.GetOptionsFromEnvironment();
      lock (FirebaseApp.Apps)
      {
        if (FirebaseApp.Apps.ContainsKey(name))
        {
          if (name == "[DEFAULT]")
            throw new ArgumentException("The default FirebaseApp already exists.");
          throw new ArgumentException("FirebaseApp named " + name + " already exists.");
        }
        FirebaseApp firebaseApp = new FirebaseApp(options, name);
        FirebaseApp.Apps.Add(name, firebaseApp);
        return firebaseApp;
      }
    }

Hence if you have multiple apps (Projects) that you want to use, then you need to use the overload with name. You can use name as ProjectId or any other Identifier.

var instance = FirebaseApp.GetInstance(appOptions.ProjectId) ?? FirebaseApp.Create(appOptions, appOptions.ProjectId);
Pickpocket answered 29/7, 2022 at 19:43 Comment(0)
F
0

After create on first time FirebaseApp stored in DefaultInstance

FirebaseApp app;
    if (FirebaseApp.DefaultInstance == null)
    {
        var file = Server.MapPath("your-acc.json");
        app = FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile(file).CreateScoped("https://www.googleapis.com/auth/firebase.messaging") });
    }else
    {
        app = FirebaseApp.DefaultInstance;
    }    
        
    FirebaseMessaging messaging = FirebaseMessaging.GetMessaging(app);
    var result = await messaging.SendAsync(CreateNotification(title, msg, DeviceToken));
Foah answered 18/10, 2023 at 3:23 Comment(0)
P
0

FirebaseApp have static dictionary for initialize. If you register one time named instance you are not able to create again same instance. The key is GetInstance method. Dont forget every firebase feature (messaging, firedb etc.) sharing instances with firebaseapp class in .Net.

If you initialize parameterless firebaseapp taking it for default instance. But if you use keyed onces there is instance register problem. I solved this problem with this static method. You can implement it anywhere.

static FirebaseApp CreateApplication(AppOptions? appOptions, string? name)
{
    if (FirebaseApp.DefaultInstance is null)
    {
        if (name.IsNullOrEmptyOrWhiteSpace())
        {
            return appOptions switch
            {
                not null when name.IsNullOrEmptyOrWhiteSpace() => FirebaseApp.Create(appOptions),
                null when name.IsNullOrEmptyOrWhiteSpace() => FirebaseApp.Create(),
                _ => FirebaseApp.Create(),
            };
        }
        else
        {
            FirebaseApp alreadyExistInstance = FirebaseApp.GetInstance(name) ??
                appOptions switch
                {
                    not null when name.IsNotNullOrEmptyOrWhiteSpace() => FirebaseApp.Create(appOptions, name),
                    not null when name.IsNullOrEmptyOrWhiteSpace() => FirebaseApp.Create(appOptions),
                    null when name.IsNotNullOrEmptyOrWhiteSpace() => FirebaseApp.Create(name),
                    null when name.IsNullOrEmptyOrWhiteSpace() => FirebaseApp.Create(),
                    _ => FirebaseApp.Create(),
                };
            return alreadyExistInstance;
        }
    }
    else
    {
        return FirebaseApp.DefaultInstance;
    }

}
Postdate answered 16/3 at 6:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.