How to Implement Dependency Injection in a Console Application?

 

Implementing dependency injection in a .NET Core console application involves setting up a ServiceCollection, configuring services, and building a service provider.

Example:

using Microsoft.Extensions.DependencyInjection;
using System;

namespace ConsoleAppDI
{
public interface IGreetingService
{
void Greet(string name);
}

public class GreetingService : IGreetingService
{
public void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
}

class Program
{
static void Main(string[] args)
{
// Setup DI
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);

var serviceProvider = serviceCollection.BuildServiceProvider();

// Get service and use it
var greeter = serviceProvider.GetService<IGreetingService>();
greeter.Greet("World");
}

private static void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IGreetingService, GreetingService>();
}
}
}

Comments

Popular posts from this blog

How to Convert Word Document to PDF using C#

Sql query to get counts by quarterly and half yearly

How to Get First Day and Last Day of a Current Quarter in SQL Server