C# Dependency Injection Methods

In C#, there are several commonly used dependency injection methods:

  1. Constructor Injection: Passing dependency objects in the class’s constructor.
public class MyClass
{
    private readonly IDependency _dependency;

    public MyClass(IDependency dependency)
    {
        _dependency = dependency;
    }

    // ...
}
  1. Property injection: Injecting dependent objects through properties.
public class MyClass
{
    public IDependency Dependency { get; set; }

    // ...
}
  1. Method Injection: Injecting dependency objects through methods.
public class MyClass
{
    public void SetDependency(IDependency dependency)
    {
        // ...
    }

    // ...
}
  1. Interface injection: Injecting dependency objects by implementing specific interfaces.
public class MyClass : IDependencyInjection
{
    public void SetDependency(IDependency dependency)
    {
        // ...
    }

    // ...
}
  1. Service Locator: Resolves dependency objects through a centralized container.
public class MyClass
{
    private readonly IDependency _dependency;

    public MyClass()
    {
        _dependency = ServiceLocator.Resolve<IDependency>();
    }

    // ...
}

Note: The above are just some common ways of dependency injection, in actual applications, different methods can be combined to meet specific needs. Additionally, third-party dependency injection containers (such as Autofac, Unity, Ninject, etc.) can also be used to simplify the dependency injection process.

bannerAds