DEV Community

Joel Jeyachandran
Joel Jeyachandran

Posted on

Dependency Injection In a .NET Core Console Application

All .Net core app types in have a DI starting point or anchor point i.e startup.cs except console application.

Here is a short guide to setup DI in a .NET Core console app.

Let's create a simple console app and the message "Hello World" lets move to an injected class later. So initially your console App's entry method (Main) will look like this.

class Program
{
    static void Main(string[] args)
    {
            Console.WriteLine("Hello World!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Now let's add some DI packages, in this case we are going to use the built in DI. So let's install the following Nuget packages.

Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Hosting
Microsoft.Extensions.Hosting.Abstractions
Enter fullscreen mode Exit fullscreen mode

Now lets add the IHost builder, to do this lets add a private static method under the Main method. This will be the main method to build our registrations, similar to a startup.cs.

private static IHostBuilder CreateHostBuilder(string[] args)
{
    var hostBuilder = Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, builder) =>
        {
            builder.SetBasePath(Directory.GetCurrentDirectory());
        })
        .ConfigureServices((context, services) =>
        {
            //add your service registrations
        });

    return hostBuilder;
}
Enter fullscreen mode Exit fullscreen mode

Now lets create a HelloService class that implements IHelloService interface, this is where we are going to move the Console Write call inside the main method above.

public interface IHelloService
{
    void WriteMessage();
}

public class HelloService : IHelloService
{
    public void WriteMessage()
    {
        Console.WriteLine("Hello World!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Next let's register this service inside .configureservices method in the CreateHostBuilder method you created above. So it should now look like this.

private static IHostBuilder CreateHostBuilder(string[] args)
{
    var hostBuilder = Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, builder) =>
        {
            builder.SetBasePath(Directory.GetCurrentDirectory());
        })
        .ConfigureServices((context, services) =>
        {
            //add your service registrations
            services.AddSingleton<IHelloService, HelloService>();
        });

    return hostBuilder;
}
Enter fullscreen mode Exit fullscreen mode

The final bit is to call your CreateHostBuilder method in the main method to wire up everything.

So now your Main method should look like this

static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    host.Services.GetService<IHelloService>().WriteMessage();
    Console.Read();
}
Enter fullscreen mode Exit fullscreen mode

Now if you run the application, you can call whatever method using injected classes as long as they are defined in the contract (interface).

Discussion (2)

Collapse
igormoskvitin profile image
Igor Moskvitin

Microsoft.Extensions.Hosting.Abstractions is not necessary. Microsoft.Extensions.Hosting has transient dependency for it.

Collapse
seanmuggin profile image
SeanMuggin

Exactly what I was looking for! Thanks!