Search code examples
c#.netwpfwindows

C# Not Sure Why Services is null


I am new to WPF application and I am not able to figure out why services.BuildServiceProvider() is null. I thought once the line where AppHost is declared is executed, ConfigureServices should have built the services object and in turn, _serviceProvider will not be null in the OnStartup method.

public partial class App : Application
{

    private readonly ServiceProvider \_serviceProvider;

    public static IHost? AppHost { get; private set; }

    public App()
    {
        ServiceCollection services = new();
        AppHost = Host.CreateDefaultBuilder()
            .ConfigureServices(ConfigureServices)
            .Build();
        **_serviceProvider = services.BuildServiceProvider();**
    }
    
    protected void ConfigureServices(HostBuilderContext context, IServiceCollection services)
    {
        services.AddSingleton<IMainViewModel, MainViewModel>();
        services.AddSingleton<MainWindow>();
        ...

    }
       
    
    protected override async void OnStartup(StartupEventArgs e)
    {
        ILogger logger = _serviceProvider.GetService<ILogger>()!;
        ...
    
        startupForm.Show();
    
        base.OnStartup(e);
    }

So my question is, why am I getting null for the services object? I know I make a mistake somewhere, could someone please point it out?


Solution

  • You do not need to create a ServiceCollection object separately because it is created and initialised when the host is created.

    IHost has Services property that contains the program's configured services.

    Also you have to change a type for _serviceProvider from Microsoft.Extensions.DependencyInjection.ServiceProvider to its abstraction System.IServiceProvider:

    private readonly IServiceProvider _serviceProvider;
    
    public App()
    {
        AppHost = Host.CreateDefaultBuilder()
            .ConfigureServices(ConfigureServices)
            .Build();
    
        _serviceProvider = AppHost.Services;
    }