C# Dependency Injection Methods
In C#, there are several commonly used dependency injection methods:
- Constructor Injection: Passing dependency objects in the class’s constructor.
public class MyClass
{
private readonly IDependency _dependency;
public MyClass(IDependency dependency)
{
_dependency = dependency;
}
// ...
}
- Property injection: Injecting dependent objects through properties.
public class MyClass
{
public IDependency Dependency { get; set; }
// ...
}
- Method Injection: Injecting dependency objects through methods.
public class MyClass
{
public void SetDependency(IDependency dependency)
{
// ...
}
// ...
}
- Interface injection: Injecting dependency objects by implementing specific interfaces.
public class MyClass : IDependencyInjection
{
public void SetDependency(IDependency dependency)
{
// ...
}
// ...
}
- 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.