Home > Enterprise >  Pass a value globally
Pass a value globally

Time:12-25

Im new to xamarin/c#, im trying to make an application with login , and Im trying to pass the logged in userid inside the application, the question is , how do I pass or make the user id keeps floating inside after the login page? Should I keep passing it in every page using queryproperty or there's better way to keep it , like a specific file to to put it so that every page can call it?

CodePudding user response:

You can use the Application.Properties collection to store things that need to be accessible to the entire application.

To store the user ID you would use

Application.Current.Properties("UserID") = UserID;

and to retrieve it you would use

UserID = Application.Current.Properties("UserID");

CodePudding user response:

In C# it's not possible to define true global variables (meaning that they don't belong to any class). using a static class is a valid alternative option so you can create something like this:

public static class Globals
{
    public Dictionary<int, UserObject> Users = new Dictionary<int, UserObject>();
}

Now, you'll be able to access The Users's dictionary property and add/remove/modify login users

Following Hans Kesting comment, Please note that An Xamarin app servers a single user at at time, so you can refactor the above from a dictionary to UserObject

CodePudding user response:

Static classes - bad practic for contains info. You can use IoC-container. I don't know xamarin, if you have startup-class (how WPF), you can make ioc-container:

  1. Install Autofac Install-Package Autofac -Version 5.0.0

  2. Rigster user content:

class StartupClass
{
   public static IContainer Container { get; set; }

   public void OnStartup()
   {
      var containerBuilder = new ContainerBuilder();
      var userContent = smthMethodForGiveUserContent();
      containerBuilder.RegisterInstance<User>(userContent); //register UserType!
      Container = containerBuilder.Build();
   }
}

  1. Resolve user content:
class SmthClass
{
   public void Method()
   {
      using(var scope = StartupClass.Container.BeginLifetimeScope())
      {
          var userContent = scope.Resolve<User>(); //IT'S YOUR OBJECT, USE!!
          //smth code..
      }
   }

}
  • Related