Mariusz Postol

Mariusz Postol

  • 644
  • 1.4k
  • 15k

Dependency Injection design pattern (DI)

Jan 31 2024 8:08 PM

I did ask GPT: Please give me a code snippet of dependency injection in C#. 

Ref: OpenAI. (2024). ChatGPT (3.5) [Large language model].

I have got the following answer:

Certainly, here's a simple example of dependency injection in C# using constructor injection:

```csharp
using System;

// Interface for the service
public interface IService
{
    void PerformAction();
}

// Implementation of the service
public class Service : IService
{
    public void PerformAction()
    {
        Console.WriteLine("Action performed by the service.");
    }
}

// Class that depends on the service through constructor injection
public class Client
{
    private readonly IService _service;

    // Constructor with IService parameter for dependency injection
    public Client(IService service)
    {
        _service = service;
    }

    public void DoWork()
    {
        // Using the injected service
        _service.PerformAction();
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Creating an instance of the service
        IService service = new Service();

        // Creating an instance of the client and injecting the service
        Client client = new Client(service);

        // Using the client
        client.DoWork();
    }
}
```

In this example, `Client` class depends on `IService`, and the dependency is injected through its constructor. The `Main` method demonstrates how you can create instances of the service and client and inject the service into the client.

The similar answer we can get from many sources. Here we have methods invocation (constructor), object instantiation, Passing parameters, abstraction (interface), and inheritance (Service inherits interface). From other sources, I know that DI is a design pattern. We use patterns to solve a problem.

What is the problem in this case?

Why do we need a special term to name something we are familiar with?


Answers (4)