Simple Dependency Injection in .NET Core Console App

If you’re using ASP.NET Core, you get dependency injection out of the box. If you’re building a console app, you can get simple dependency injection with just a little bit of code.

For basic mapping, all you need is to create a ServiceProvider object that maps  your types, and your constructor injection works perfectly. Here’s a working sample:

// dotnet add package Microsoft.Extensions.DependencyInjection
class Program {

// Map your items. Note that you can map a class to itself.
private static ServiceProvider _serviceProvider = new ServiceCollection()
.AddTransient<Program, Program>()
.AddTransient<IManager, Manager>()
.AddTransient<IRepository, Repository>()

// Uses the service provider to retrieve a Program instance and call Go()
static void Main() => _serviceProvider.GetService<Program>().Go();

// Constructor injection pulls in a Manager object
private readonly IManager _manager;
public Program(IManager manager) => _manager = manager;

public void Go() => _manager.Go();

public interface IManager { void Go(); }

public class Manager : IManager {

// Constructor injection pulls in a Repository object
private readonly IRepository _repo;
public Manager(IRepository repo) => _repo = repo;

void IManager.Go() => Console.WriteLine(_repo.Hello("world"));

public interface IRepository { string Hello(string name); }

public class Repository : IRepository {
string IRepository.Hello(string name) => $"Hello {name}";


Leave a Reply

Your email address will not be published.