I created a class AppConfig :
public class AppConfig
{
private readonly IConfigurationRoot _configurationRoot;
public AppConfig()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Package.Current.InstalledLocation.Path)
.AddJsonFile("appsettings.json", optional: false);
_configurationRoot = builder.Build();
}
private T GetSection<T>(string key) => _configurationRoot.GetSection(key).Get<T>();
public Config Config => GetSection<Config>(nameof(Config));
}
And I use it like this in my ViewModels :
var config = new AppConfig();
But is there a better way to use this with Dependency Injection.
So that I can add it in the ViewModelLocator like other services?
public ViewModelLocator()
{
SimpleIoc.Default.Register<ITestService, TestService>();
SimpleIoc.Default.Register<MainViewModel>();
}
Or how would you do this in a UWP application with the MvvmLightLibsStd10?
Create in interface that abstracts the desired class.
public interface IAppConfig {
Config Config { get; }
}
Derive the class from the interface
public class AppConfig : IAppConfig {
//...omitted for brevity
}
and register the abstraction and implementation with the container
//...
SimpleIoc.Default.Register<IAppConfig, AppConfig>();
//...
Any thus class that needs use of the config can depend on it explicitly via constructor injection