Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use MAUI IAppInfo with Microsoft.Extensions.DependencyInjection

I’ve been using my own little AppInfo class with Microsoft.Extensions.DependencyInjection, but ran into a cross-platform issue with it, so now I want to switch to using the built-in MAUI AppInfo, but I’m having issues with getting it registered in the DI.

So, the code I have working with my own class was (just the relevant bits)…

using Microsoft.Extensions.DependencyInjection;
using MyAppInfoNamespace;
// other stuff
MauiAppBuilder builder=MauiApp.CreateBuilder();
builder.Services
    .AddSingleton<IMyAppInfo,MyAppInfoImplementation>()
//other services
    ;
// rest of builder code

I removed the using for my library, as well as the link to the DLL, and added…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using Microsoft.Maui.ApplicationModel;

The issue I’m having is with getting the rest of the syntax working.

If I put…

    .AddSingleton<IAppInfo,AppInfo>()

which is the same syntax I used with my own class, just altered appropriately, VS tells me "static types cannot be used as type arguments"

but if I put just…

    .AddSingleton<IAppInfo>()

then I get…

Cannot instantiate implementation type ‘Microsoft.Maui.ApplicationModel.IAppInfo’ for service type ‘Microsoft.Maui.ApplicationModel.IAppInfo’.

When I Google these error messages I can only find stuff not about MAUI. So what do I need to do to get the AddSingleton line of code working with MAUI AppInfo? I’ve run out of things to try.

thanks,
Donald.

>Solution :

As u mentioned AppInfo is a static class. But AppInfo has the property Current.

public static IAppInfo Current { get; }

This is what you need to add to the container.

builder.Services.AddSingleton(AppInfo.Current);

If you wonder, this is the same as

builder.Services.AddSingleton<IAppInfo>(AppInfo.Current);

Example for Constructor Injection

public AboutViewModel(IAppInfo appinfo)
{
    VersionString = appinfo.VersionString;
    PackageName = appinfo.PackageName;
    Name = appinfo.Name;
    Build = appinfo.BuildString;
}

Edit:
you don’t need the using statement:

using Microsoft.Extensions.DependencyInjection;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading