In order to have dependency injection in .NET Core consol applications you will need to install the package
Microsoft.Extensions.DependencyInjection
Before we get into the bootstrapping the console application, lets create a few services. The first service is an email service with a single method.
public interface IEmailService
{
Task SendMailAsync(string from, string to, string subject, string body);
}
public class EmailService : IEmailService
{
public Task SendMailAsync(string from, string to, string subject, string body)
{
// implement details of sending mail here...
}
}
The second service is for running our application, it takes IEmailService
as a dependency in the constructor.
public interface IAppService
{
Task RunAsync();
}
public class AppService : IAppService
{
public AppService(IEmailService emailService)
{
_emailService = emailService;
}
IEmailService _emailService;
public Task Run()
{
// application logic goes here
// send an email when done
}
}
Now that we have some depenencies, let's use them. The code below will do four things
- Create a
ServiceCollection
instance - Configure the services
- Create a
ServiceProvider
that can be used to resolve dependencies - Resolve and use one of our services
using Microsoft.Extensions.DependencyInjection;
namespace ConsoleDependencyInjection
{
class Program
{
static void Main(string[] args)
{
// configure services
var services = new ServiceCollection()
.AddTransient<IAppService, AppService>()
.AddTransient<IEmailService, EmailService>();
// create a service provider from the service collection
var serviceProvider = services.BuildServiceProvider();
// resolve the dependency graph
var appService = serviceProvider.GetService<IAppService>();
// run the application
appService.RunAsync().Wait();
}
}
}
The first step was creating the service collection.
var services = new ServiceCollection();
The service collection has extension methods for configuring various service types. It also has the AddTransient
, plus others, for configuring your own services quickly.
This should be familiar territory for anyone who has used the ConfigureServices
method of a .NET MVC Core application.
Once services are configured, build a IServiceProvider
so that you can resolve your application code and execute it. The IServiceProvider
has GetService
and GetRequiredService
method that allow you to retrieve your service. The latter will throw an exception if the service cannot be resolved.
That's all there is to it!