Nandini Chatterjee
Nandini Chatterjee

Reputation: 13

How to add custom service to wpf prism project which will be accessible in all viewmodels?

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

Upvotes: 1

Views: 964

Answers (1)

Anindya
Anindya

Reputation: 2686

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.

Upvotes: 2

Related Questions