how to use Command line parameter in viewmodel (MVVM Model) wpf application
Asked Answered
R

1

5

I have an WPF application which can take command line parameter. I want to use this command line parameter in ViewModel, I have following options to do that.

1) create public static variable in app.xaml.cs . read command line parameter value in main method and assign it to public static variable. that can be accessed in viewmodel using App.variablename.

2) create environment variable like System.Environment.SetEnvironmentVariable("CmdLineParam", "u") and later use it in viewmodel with Environment.GetEnvironmentVariable("CmdLineParam").

I want to ask which approach is good considering MVVM pattern and if there is better method to achieve this.

Rail answered 5/10, 2013 at 11:10 Comment(0)
L
18

I do not think that this issue is related to MVVM at all. A good way to make the command line arguments available to a view model might be to (constructor) inject a service. Let's call it IEnvironmentService:

public interface IEnvironmentService
{
  IEnumerable<string> GetCommandLineArguments();
}

The implementation would then use Environment.GetCommandLineArgs (which returns a string array containing the command-line arguments for the current process):

public class MyProductionEnvironmentService : IEnvironmentService
{
  public IEnumerable<string> GetCommandLineArguments()
  {
    return Environment.GetCommandLineArgs();
  }
}

Your view model would then look like this:

public class MyViewModel
{
  public MyViewModel(IEnvironmentService service)
  {
    // do something useful here
  }
}

All you have to do now is create and insert the production environment service at run-time (passing it yourself, having it created by IoC container etc.). And use a fake/mock one for unit testing.

Lui answered 5/10, 2013 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.