Dependency Injection in .Net Core Console

To demonstrate Dependency Injection in a .Net Core Console project, I will create a SecurityService class which will have a dependency on an AuditService class.

The SecurityService will allow a user to login, and then use the AuditService to write an audit log entry (in this case just to the console).

Each of these class will have a corresponding Interface.

Interfaces:

public interface ISecurityService
{
    void Login();
}

public interface IAuditService
{
    void Log();
}

The implementation of these interfaces are:

public class SercurityService : ISecurityService
{
    private readonly IAuditService _auditService;

    public SercurityService(IAuditService auditService)
    {
        _auditService = auditService;
    }
    
    public void Login()
    {
        Console.WriteLine("Log user in");
        _auditService.Log();
    }
}

public class AuditService : IAuditService
{
    public void Log()
    {
        Console.WriteLine("Audit action");
    }
}

To wire all this up we need to add the following NuGet package to our project: * Microsoft.Extensions.DependencyInjection;

The Dependency Inject is wired up as follows:

class Program
{
    static void Main(string[] args)
    {
        //Register the services
        var serviceProvider = new ServiceCollection()
            .AddSingleton<ISecurityService, SercurityService>()
            .AddSingleton<IAuditService, AuditService>()
            .BuildServiceProvider();
    
        //Instantiate the security helper, and call the login method
        var secutityHelper = serviceProvider.GetService<ISecurityService>();
        secutityHelper.Login();
    
        Console.Read();
    }
}

This will give the following output:

Log user in
Audit action
Alex Orpwood Written by:

Software developing and architecting for 20 years. Satellite monitoring by day, writing my own app by night. More about me