Reputation: 505
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.
Upvotes: 5
Views: 3564
Reputation: 3280
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.
Upvotes: 18