//Define the IEngine Interface
public interface IEngine
{
void Start();
}
//Implement the IEngine Interface
public class GasEngine : IEngine
{
public void Start()
{
Console.WriteLine("Gas Engine Started");
}
}
public class ElectricEngine : IEngine
{
public void Start()
{
Console.WriteLine("Electric Engine Started");
}
}
//Define the Car Class that Depends on IEngine
public class Car
{
private readonly IEngine _engine;
// Constructor Injection: Engine is injected via the constructor
public Car(IEngine engine)
{
_engine = engine;
}
public void StartCar()
{
_engine.Start(); // Delegates the start functionality to the injected engine
}
}
using Microsoft.Extensions.DependencyInjection;
using System;
class Program
{
static void Main()
{
// Step 1: Create a DI container and configure services
var serviceProvider = new ServiceCollection()
.AddTransient() // Register GasEngine to IEngine interface
.AddTransient() // Register Car (transient, will be disposed)
.BuildServiceProvider();
// Step 2: Use the 'using' block to automatically manage resources
using (var scope = serviceProvider.CreateScope()) // Start a scope for DI container
{
var car = scope.ServiceProvider.GetService();
car.StartCar();
} // Once the 'using' block ends, all resources (including IEngine) are disposed
// Here, we can see that the engine is disposed of automatically when it's no longer needed
}
}