In .NET Core 2, the dependency injection, comes as a feature - you don't need to add packages like Unity etc. This is the official documentation.
Basically, when having a .NET Core application, you have the entry point Program.cs
and the Startup.cs
files, that are executed on the initial start of the application.
The 'magic' with dependency injection happens in the Startup.cs
. There (by default) you have
public void ConfigureServices(IServiceCollection services)
{
/// code
}
To add an injection you need to do something like:
services.AddTransient<IMyInterface, MyClassImplementingMyInterface>();
Except AddTransient
there are 2 more possibilities, defining the lifetime of your service. They are: AddSingleton
and AddScoped
. This answer, and the documentation, that I mentioned above, give a good explanation of the meaning of all of them, but in a few words:
Depending on how we configure the lifetime for this service, the
container will provide either the same or different instances of the
service to the requesting class.
AddTransient
- the objects are always different; a new instance is
provided to every controller and every service.
AddScoped
- the objects are the same within a request, but
different across different requests
AddSingleton
- the objects are the same for every object
and every request (regardless of whether an instance is provided in
ConfigureServices)