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
Post a Comment