This post describes the foundational steps to configure the Microsoft dependency injection container for a C# console application.
Once you have a basic console application, you need to install the following Nuget packages:
The following code is the barest basics for configuring the Microsoft.Extensions.Hosting.Host
.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
IHost host = Host.CreateDefaultBuilder(args)
.Build();
// do stuff
await host.RunAsync();
The Host
static class has a single method CreateDefaultBuilder
.
The CreateDefaultBuilder
method is interesting as it does a lot of really helpful stuff for us. Per the documentation, it:
That’s a lot of useful stuff that we don’t have to do by hand. It means we can do things like:
Finally, we need to call Build()
. Without this, we will create an instance of IHostBuilder
. Build()
belongs to the IHostBuilder
interface and we use it to create an instance of IHost
.
Microsoft provides documentation for the dependency injection container here.
From here, things are pretty much identical to configuring the DI container in a WebAPI app.
Chaining on the ConfigureServices()
method allows you to configure the dependency injection container. In the sample below, I am injecting two services.
services.AddSingleton<IDataAccess, DataAccess>();
IDataAccess
contract to resolve to the DataAccess
type.services.AddSingleton<DataAccess.CreateDbConnection>((serviceProvider) =>{});
DataAccess.CreateDbConnection
is a delegate type. In the code contained inside the parens, I am configuring the IDbConnection
type that Dapper is using depending on the value in the ASPNET_ENVIRONMENT
environment variable. var host = Host.CreateDefaultBuilder(args).ConfigureServices(
services =>
{
services.AddSingleton<IDataAccess, DataAccess>();
services.AddSingleton<DataAccess.CreateDbConnection>((serviceProvider) =>
{
var config = serviceProvider.GetRequiredService<IConfiguration>();
var aspnetEnvironment = config.GetSection("ASPNET_ENVIRONMENT").Value;
Console.WriteLine($"ASPNET_ENVIRONMENT: {aspnetEnvironment}");
return aspnetEnvironment switch
{
"Development" => SqlConnectionProvider.CreateDbConnection,
"Test" => SqliteConnectionProvider.CreateInMemoryDbConnection,
_ => SqliteConnectionProvider.CreateDbConnection
};
});
}
).Build();
I have created a sample console application that is using the Microsoft dependency injection container. Here is the direct link to the Program.cs file.
This demo application uses Dapper to access a database. There are a couple of issues right now relating to the creation of the in memory SQLite DB but otherwise it illustrates of using Dapper and configuring the database connection using dependency injection.