Service Provider in .NET MAUI

namespace Temptor.Helpers
{
    public static class ServiceProvider
    {
        public static TService GetService<TService>()
        {
            return Current.GetService<TService>();
        }

        public static IServiceProvider Current
        {
            get 
            {
                #if WINDOWS10_0_17763_0_OR_GREATER
                    return MauiWinUIApplication.Current.Services;
                #else
                    return null;
                #endif
            }
        }
    }
}
No need to use constructor injection for any service if necessary:
namespace Temptor.Models
{
    public class Property
    {
        public PropertyService ropertyService;

        ...

        public Property() 
        {
            this.PropertyService = Helpers.ServiceProvider.GetService<PropertyService>();

            ...
        }
    }
}

No comments:

Post a Comment