Adding Dependency Injection to a Console App in .Net 7

March 10, 2023

Like many people, I create a fair number of console apps. Most of the time, they’re two or three lines of code to test an idea out, but occasionally, I’ll create one that actually might be useful again. I’ve ended up at Google’s door more than once to work out how to add DI to my console app - so, I’m creating this, so that next time, I can find it on my site.

This was written and tested using .Net 7. I believe it will work in any version of .Net Core.

NuGet

The first step is to add Hosting and DI to your project:

Install-Package Microsoft.Extensions.DependencyInjection
Install-Package Microsoft.Extensions.Hosting

IHost

In program.cs, you’ll need to configure a IHost:

using IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddSingleton<SomeClass>();
        services.AddHttpClient();
        services.AddDbContext<MyDbContext>();
    })
    .Build();

// code

await host.RunAsync();

For example:

using IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddSingleton<MyClass2>();        
        services.AddSingleton<MyClass>();        
    })
    .Build();

var myClass = host.Services.GetService<MyClass>();
await myClass!.DoStuff();

await host.RunAsync();

Then, in MyClass:



public class MyClass
{
    private readonly MyClass2 _class2;    

    public MyClass(MyClass2 class2)
    {
        _class2 = class2;        
    }

    public async Task DoStuff()
    {
        ...

That’s pretty much it.

References

If you’re interested in my musings on console applications, you might find one of the following interesting:

Unit Testing an interactive console application

Using a console application as a harness to create a performance test

A catch game inside a console application

A snake game inside a console application



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024