Dependency Injection in .NET using C#

/** 
MessageWriter class is the dependency of the Worker class
source: https://docs.microsoft.com/en-us/dotnet/core/exteDependency injection in .NET | Microsoft Docsnsions/dependency-injection
*/
public class MessageWriter {
public void Write(string message) {
Console.WriteLine($"MessageWriter.Write(message: \"{message}\")");
}
}

public class Worker : BackgroundService {
private readonly MessageWriter _messageWriter = new MessageWriter();
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellation Requested) {
_messageWriter.Write($"Worker running at: {DateTimeOffset.Now}");
await Task. Delay(1000, stoppingToken);
}
}
}

What are the problems?

How to solve these issues using DI?

Code Snippets

/** 
Create interface IMessageWriter and rewrite MessageWriter to implement IMessageWriter
source: https://docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
*/
using System;
namespace DependencyInjection.Example {
public interface IMessageWriter {
void Write(string message);
}
}
namespace DependencyInjection.Example {
public class MessageWriter : IMessageWriter {
public void Write(string message) {
Console.WriteLine($"MessageWriter.Write(message: \"{message}\")");
}
}
}
/** 
Register to the service container with its concrete implementation MessageWriter
source: https://docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
*/
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace DependencyInjection.Example {
class Program {
static Task Main(string[] args) => CreateHostBuilder (args).Build().RunAsync();
static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureServices((_, services) => services.AddHostedService<Worker>().AddScoped<IMessageWriter, MessageWriter>());
}
}
/**
Worker class request for IMessageRequest. The DI container will provide the instance.
source: https://docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
namespace DependencyInjection.Example {
public class Worker : BackgroundService {
private readonly IMessageWriter _messageWriter;
public Worker (IMessageWriter messageWriter) => _messageWriter = messageWriter;
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested) {
_messageWriter.Write($"Worker running at: {DateTimeOffset. Now}");
await Task. Delay(1000, stoppingToken);
}
}
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store