How to use maui preferences in class library?

vijay ravuri 0 Reputation points
2024-04-05T10:32:14.5766667+00:00

Hi,

I have created one Maui application and in the same solution created one class library to maintain services.(please refer solution image)

Now I need to store one value in preferences in service class. But service class in class library.

So how can we access preferences in class library.

Note: if it is a Maui Class library then we can use preferences as it has Microsoft.Maui.Essentials. But I need to use Preferences in Class library only.

Please suggest mesolution

, Thanks.

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,895 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Johan Smarius 390 Reputation points MVP
    2024-04-05T20:07:15.1433333+00:00

    If you really want to use a regular assembly for the service, you could use dependency injection to help you.

    Create an interface in your service project to allow the setting and retrieval of preferences:

    User's image

    In the Maui project create an implementation of this interface. You can use the code from the Preferences class for this (https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/storage/preferences?view=net-maui-8.0&tabs=windows)

    User's image

    And use the Service collection to combine the 2.

    User's image

    I have included MainPage as well, because I use this Page to inject the interface into.

    User's image

    The entire code can be found at: https://github.com/JohanSmarius/DependenciesInMaui

    0 comments No comments

  2. vijay ravuri 0 Reputation points
    2024-04-08T04:44:22.29+00:00

    Hi @Johan Smarius , thanks for reply. I have implemented the solution and working fine.

    And I got another solution also...

    Using a <UseMaui>true</UseMaui> in csproj file is enabling to install microsoft essentials. so then i was able to use preferences in class library too.

    0 comments No comments