1

I'm developing a WPF app used by multiple persons on a network. On startup I want to get the user name from Environment.UserName and retrieve the user account from my database, then create a User object.

Where should I do the user initialization? It seems logical to add a member User currentUser to the Application and do the initialization in the Main() method, for example:

public class App : Application {
    public User CurrentUser {
        get; private set;
    }
    private Database database = new Database();

    public static void Main() {
        App app = new App();
        CurrentUser = database.getUser(Environment.UserName);
        app.InitializeComponent();
        app.Run();
    }
}

However I'm having doubts since the Main() is auto generated in WPF.

Queder
  • 310
  • 3
  • 11
  • 1
    application has `Startup` event. add event handler and do initialization there – ASh Aug 01 '17 at 12:28
  • 2
    Who told you that Main is auto-generated? You can do whatever you want in your Main method – Camilo Terevinto Aug 01 '17 at 12:28
  • By default, `Main()` is auto generated and can be found in the `obj` folder (`obj\Debug\App.g.i.cs`). I know you can modify it manually but I don't know what the best practices in WPF are regarding `Main()` modifications. – Queder Aug 01 '17 at 12:32
  • 1
    The answer is here: https://stackoverflow.com/questions/9504939/how-to-stop-main-from-being-auto-generated-in-wpf – Palle Due Aug 01 '17 at 12:35

1 Answers1

4

Override the OnStartup method in the App class in App.xaml.cs.

Please refer to the following blog post for more information about how you could implement custom authorization in WPF: https://blog.magnusmontin.net/2013/03/24/custom-authorization-in-wpf/

mm8
  • 163,881
  • 10
  • 57
  • 88