.NET Dependecy Injection - What's in IHost for me?

Viewed 17

Going through the .NET Dependency Injection documentation, I can't figure out what the IHost interface does for me or if I need it at all in my case.

I'm building a Desktop application, but since there's a lot of changes going on /wrt to Microsoft UI Frameworks, I want to encapsulate the main application logic from the UI as much as possible. So we're starting with a WPF frontend, but may switch later on to WinUI3, or may also add a Console App on-top. For this, I crated a .NET library project called Core.

In terms of DI, Core provides the DI infrastructure and sets up basic stuff like logging. UI can also use this infrastructure by implementing IUIServiceHelper.

From what I've seen, IHost should represent the application (lifecycle), so do I need it at all in this context, when DI is decoupled from the applications entry point?

That's what my WPF App.xaml.cs looks like:

public partial class App : Application, Core.DI.IUIServiceHelper
{
    public App()
    {
        AppHost.RunAsync(this);
    }

    void IUIServiceHelper.AddServices(IServiceCollection services)
    {
        services.AddSingleton<MainWindow>();
    }

    private void OnStartup(object sender, StartupEventArgs e)
    {
        var mainWindow = AppHost.ServiceProvider?.GetService<MainWindow>();
        mainWindow?.Show();
    }
}

And here's what's the AppHost class from Core looks like:

namespace Core.DI;
public static class AppHost
{
    private static IHost? _host;
    public static IServiceProvider? ServiceProvider
    {
        get => _host?.Services;
    }

    public static void RunAsync(IUIServiceHelper uiServiceProvider)
    {
        var builder = Host.CreateDefaultBuilder();
        builder.ConfigureServices(services =>
        {
            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.ClearProviders();
                loggingBuilder.SetMinimumLevel(LogLevel.Debug);
                // loggingBuilder.AddNLog(GetNLogConfig());
            });

            uiServiceProvider.AddServices(services);
        });

        _host = builder.Build();
        _host.RunAsync();
    }
}

This way, I think, I can always change my UI project and reuse DI from Core. But there's so many questions involving this IHost object, e.g. since it runs async, does it need to be fully started already in order to be able to provide .Services (IServiceProvider)?

  • And most importantly, do I need it at all, or would it be enough to create a ServiceCollection and run .BuildServiceProvider() once, ie. can I drop this host related stuff at all?

  • Is the way I plan to integrate DI in my application a valid one? Any better ways to do this?

Thank you!

0 Answers
Related