Design Patterns

Example 2: Interface-Based Dependency Injection

In this example, we'll use an interface to define dependencies, allowing for different implementations to be injected:

Repository Interface

public interface IRepository
{
    void Add(T entity);
    void Update(T entity);
    void Delete(T entity);
}

Concrete Repository Implementation

public class UserRepository : IRepository
{
    public void Add(User entity)
    {
        Console.WriteLine($"Adding user: {entity.Name}");
    }

    public void Update(User entity)
    {
        Console.WriteLine($"Updating user: {entity.Name}");
    }

    public void Delete(User entity)
    {
        Console.WriteLine($"Deleting user: {entity.Name}");
    }
}

User Entity Class

public class User
{
    public string Name { get; set; }
    // Other user properties
}

Service Class with Interface Injection

public class UserService
{
    private readonly IRepository _repository;

    // Constructor Injection with IRepository
    public UserService(IRepository repository)
    {
        _repository = repository;
    }

    public void RegisterUser(User user)
    {
        _repository.Add(user);
        // Additional business logic
    }
}

Dependency Injection Setup and Usage

class Program
{
    static void Main(string[] args)
    {
        // Setup DI container (manually without a framework)
        IRepository userRepository = new UserRepository();
        UserService userService = new UserService(userRepository);

        // Use the UserService with injected UserRepository
        User newUser = new User { Name = "John Doe" };
        userService.RegisterUser(newUser);
    }
}