- Constructor requires to be
public
and only one applicable constructor exist.
- Constructor overloads are supported, but only one overload can exist whose arguments can all be fulfilled by dependency injection.
- Constructors can accept arguments that are not provided by dependency injection, but these must support default values.
- The
ConfigureServices
method in the Startup class is responsible for defining the services the application will use.
- Creating the requested object, and all of the objects it requires is sometimes referred to as an object graph.
- Likewise, the collective set of dependencies that must be resolved is typically referred to as a dependency tree or dependency graph.
- Services that have dependencies should register them in the container.
- The dependency injection can be used in a chained fashion, with each requested dependency in turn requesting its own dependencies.
- The container is responsible for resolving all of the dependencies in the graph and returning the fully resolved service.
Service Lifetimes and Registration Options
Transient
- Transient lifetime services are created each time they're requested.
- This lifetime works best for lightweight, stateless services.
- The
AddTransient
method is used to map abstract types to concrete services that are instantiated separately for every object.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
Scoped
- Scoped lifetime services are created once per request.
- If you're using a scoped service in a middleware, inject the service into the
Invoke
or InvokeAsync
method.
- Don't inject via constructor injection because it forces the service to behave like a singleton.
- Scoped objects are the same within a request, but different across different requests.
services.AddScoped<IMyDependency, MyDependency>();
Singleton
- Singleton lifetime services are created the first time they're requested (or when
ConfigureServices
is run if you specify an instance there) and then every subsequent request will use the same instance.
- If your application requires singleton behavior, allowing the services container to manage the service's lifetime is recommended.
services.AddSingleton<IOperationSingleton, Operation>();
services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty));