Dependency injection (DI) in .NET Core is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. It promotes loose coupling, testability, and maintainability by allowing the runtime to provide required dependencies instead of hardcoding them within classes.
.NET Core’s built-in DI container differs from other frameworks like Autofac or Ninject in its simplicity and lightweight nature. While it provides basic features such as constructor, property, and method injection, it lacks advanced capabilities like interception or auto-registration. However, it can be easily replaced with third-party containers if needed.
In .NET Core, services are registered in the ConfigureServices method of the Startup class using IServiceCollection extension methods like AddTransient, AddScoped, and AddSingleton. These methods define the lifetime of the service instances.
Example:
public void ConfigureServices(IServiceCollection services)
services.AddTransient<IMyService, MyService>();
To consume these services, simply add a parameter of the desired type in the constructor of the dependent class:
private readonly IMyService _myService;
public MyClass(IMyService myService)