create class with dependency injection in csharp

To create a class with dependency injection in C#, you need to make use of constructors and inversion of control (IoC) techniques. Here's an example of how to create a class with dependency injection in C# using the constructor injection approach:

main.cs
public interface IMyDependency
{
    void DoSomething();
}

public class MyDependency : IMyDependency
{
    public void DoSomething()
    {
        Console.WriteLine("Doing something");
    }
}

public class MyClass
{
    private readonly IMyDependency _myDependency;

    public MyClass(IMyDependency myDependency)
    {
        _myDependency = myDependency;
    }

    public void DoSomethingWithDependency()
    {
        _myDependency.DoSomething();
    }
}
462 chars
28 lines

In this example, we have a IMyDependency interface that specifies the contract for our dependency, and a concrete implementation of that interface called MyDependency.

Next, we have our main class MyClass that requires IMyDependency as a dependency. We define the dependency in the constructor of the class with IMyDependency myDependency as a parameter. This means that any time a new instance of MyClass is created, an instance of the IMyDependency dependency also needs to be passed in.

Finally, we have a method called DoSomethingWithDependency() that makes use of the dependency by calling the DoSomething() method on it.

By using constructor injection and IoC, we can easily swap out the implementation of IMyDependency at runtime without affecting the implementation of MyClass.

gistlibby LogSnag