1

I am working on application WPF in Prism framework. Now I need two things . 1. a custom dialog box to show various custom messages and 2. Save and update and get Application Settings from a file stored in system by Json .

Now I have created a class which does the Jason related stuffs and have few APIs like get and set and save obj to Json and Json to Obj. Now I need this operations in all ViewModels of my class . I do not want to create an instance of this class in all ViewModels separately.

So , I am looking for some prism supported services which can help in this direction. I have seen this question (What exactly are "WPF services"?) but it is not giving me what I want or may be I am understanding the answers in this question.

I would be obliged if someone gives me a hints in this regards

  • Are you looking for guidance about using a static method to read the settings file, or do you want to use Dependency Injection to setup a service that gets injected into your various ViewModel classes? – jeoffman Sep 13 '20 at 17:46
  • You are right . I am looking for use of Dependency Injection to setup a service that gets injected to all ViewModels in my project. . – Nandini Chatterjee Sep 14 '20 at 17:14

1 Answers1

2

First create an interface IJsonService and implement this on a class JsonService.

add these two functions in Interface IJsonService : object DeSerializeJsonToObject(string fileName); void SerializeObjectToJson(object obj);

Now in App.xaml.cs write the following code to register the service.

protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterSingleton<IJsonService, JsonService>();
    }

Now go to any viewmodel where you want this service. Create a field like JsonService . Modify the constuctor of the ViewModel like following :

IEventAggregator eventAggregator;
IJsonService JsonService;

public SensorConfigViewModel(IEventAggregator _eventAggregator,
                                     IJsonService jsonService)
        {
            this.eventAggregator = _eventAggregator;
            this.JsonService = jsonService;
}

Now you can access methods declared in the interface IJsonService and which are implemented in function in JsonService.cs

Just type JsonService.DeSerializeJsonToObject(....) and you can access the service methods. I have used latest Prism nuget packages. In old Prism packages there could be some differences.

Anindya
  • 2,616
  • 2
  • 21
  • 25