Di Private
![](/file/c626156d7f549d1c8dac8.gif)
π ALL INFORMATION CLICK HERE ππ»ππ»ππ»
Di Private
Table of contents
Exit focus mode
Light
Dark
High contrast
Light
Dark
High contrast
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.
For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core .
For information on using dependency injection in applications other than web apps, see Dependency injection in .NET .
For more information on dependency injection of options, see Options pattern in ASP.NET Core .
This topic provides information on dependency injection in ASP.NET Core. The primary documentation on using dependency injection is contained in Dependency injection in .NET .
A dependency is an object that another object depends on. Examine the following MyDependency class with a WriteMessage method that other classes depend on:
A class can create an instance of the MyDependency class to make use of its WriteMessage method. In the following example, the MyDependency class is a dependency of the IndexModel class:
The class creates and directly depends on the MyDependency class. Code dependencies, such as in the previous example, are problematic and should be avoided for the following reasons:
Dependency injection addresses these problems through:
In the sample app , the IMyDependency interface defines the WriteMessage method:
This interface is implemented by a concrete type, MyDependency :
The sample app registers the IMyDependency service with the concrete type MyDependency . The AddScoped method registers the service with a scoped lifetime, the lifetime of a single request. Service lifetimes are described later in this topic.
In the sample app, the IMyDependency service is requested and used to call the WriteMessage method:
By using the DI pattern, the controller or Razor Page:
The implementation of the IMyDependency interface can be improved by using the built-in logging API:
The updated Program.cs registers the new IMyDependency implementation:
MyDependency2 depends on ILogger , which it requests in the constructor. ILogger is a framework-provided service .
It's not unusual to use dependency injection in a chained fashion. Each requested dependency in turn requests its own dependencies. The container resolves the dependencies in the graph and returns the fully resolved service. The collective set of dependencies that must be resolved is typically referred to as a dependency tree , dependency graph , or object graph .
The container resolves ILogger by taking advantage of (generic) open types , eliminating the need to register every (generic) constructed type .
In dependency injection terminology, a service:
The framework provides a robust logging system. The IMyDependency implementations shown in the preceding examples were written to demonstrate basic DI, not to implement logging. Most apps shouldn't need to write loggers. The following code demonstrates using the default logging, which doesn't require any services to be registered:
Using the preceding code, there is no need to update Program.cs , because logging is provided by the framework.
The ASP.NET Core framework uses a convention for registering a group of related services. The convention is to use a single Add{GROUP_NAME} extension method to register all of the services required by a framework feature. For example, the AddControllers extension method registers the services required for MVC controllers.
The following code is generated by the Razor Pages template using individual user accounts and shows how to add additional services to the container using the extension methods AddDbContext and AddDefaultIdentity :
Consider the following which registers services and configures options:
Related groups of registrations can be moved to an extension method to register services. For example, the configuration services are added to the following class:
The remaining services are registered in a similar class. The following code uses the new extension methods to register the services:
Note: Each services.Add{GROUP_NAME} extension method adds and potentially configures services. For example, AddControllersWithViews adds the services MVC controllers with views require, and AddRazorPages adds the services Razor Pages requires. We recommended that apps follow the naming convention of creating extension methods in the Microsoft.Extensions.DependencyInjection namespace. Creating extension methods in the Microsoft.Extensions.DependencyInjection namespace:
To use scoped services in middleware, use one of the following approaches:
It's common to use multiple implementations when mocking types for testing .
Registering a service with only an implementation type is equivalent to registering that service with the same implementation and service type. This is why multiple implementations of a service cannot be registered using the methods that don't take an explicit service type. These methods can register multiple instances of a service, but they will all have the same implementation type.
Any of the above service registration methods can be used to register multiple service instances of the same service type. In the following example, AddSingleton is called twice with IMyDependency as the service type. The second call to AddSingleton overrides the previous one when resolved as IMyDependency and adds to the previous one when multiple services are resolved via IEnumerable . Services appear in the order they were registered when resolved via IEnumerable<{SERVICE}> .
By default, Entity Framework contexts are added to the service container using the scoped lifetime because web app database operations are normally scoped to the client request. To use a different lifetime, specify the lifetime by using an AddDbContext overload. Services of a given lifetime shouldn't use a database context with a lifetime that's shorter than the service's lifetime.
To demonstrate the difference between service lifetimes and their registration options, consider the following interfaces that represent a task as an operation with an identifier, OperationId . Depending on how the lifetime of an operation's service is configured for the following interfaces, the container provides either the same or different instances of the service when requested by a class:
The following Operation class implements all of the preceding interfaces. The Operation constructor generates a GUID and stores the last 4 characters in the OperationId property:
The following code creates multiple registrations of the Operation class according to the named lifetimes:
The sample app demonstrates object lifetimes both within and between requests. The IndexModel and the middleware request each kind of IOperation type and log the OperationId for each:
Similar to the IndexModel , the middleware resolves the same services:
Scoped and transient services must be resolved in the InvokeAsync method:
To reduce the logging output, set "Logging:LogLevel:Microsoft:Error" in the appsettings.Development.json file:
The following code shows how to resolve a scoped service for a limited duration when the app starts:
For more information, see Scope validation .
Services and their dependencies within an ASP.NET Core request are exposed through HttpContext.RequestServices .
The framework creates a scope per request, and RequestServices exposes the scoped service provider. All scoped services are valid for as long as the request is active.
Prefer requesting dependencies as constructor parameters over resolving services from RequestServices . Requesting dependencies as constructor parameters yields classes that are easier to test.
When designing services for dependency injection:
If a class has a lot of injected dependencies, it might be a sign that the class has too many responsibilities and violates the Single Responsibility Principle (SRP) . Attempt to refactor the class by moving some of its responsibilities into new classes. Keep in mind that Razor Pages page model classes and MVC controller classes should focus on UI concerns.
The container calls Dispose for the IDisposable types it creates. Services resolved from the container should never be disposed by the developer. If a type or factory is registered as a singleton, the container disposes the singleton automatically.
In the following example, the services are created by the service container and disposed automatically:
dependency-injection\samples\6.x\DIsample2\Services\Service1.cs
The debug console shows the following output after each refresh of the Index page:
Avoid using the service locator pattern . For example, don't invoke GetService to obtain a service instance when you can use DI instead:
Another service locator variation to avoid is injecting a factory that resolves dependencies at runtime. Both of these practices mix Inversion of Control strategies.
Avoid static access to HttpContext (for example, IHttpContextAccessor.HttpContext ).
DI is an alternative to static/global object access patterns. You may not be able to realize the benefits of DI if you mix it with static object access.
Orchard Core is an application framework for building modular, multi-tenant applications on ASP.NET Core. For more information, see the Orchard Core Documentation .
See the Orchard Core samples for examples of how to build modular and multi-tenant apps using just the Orchard Core Framework without any of its CMS-specific features.
Program.cs registers services that the app uses, including platform features, such as Entity Framework Core and ASP.NET Core MVC. Initially, the IServiceCollection provided to Program.cs has services defined by the framework depending on how the host was configured . For apps based on the ASP.NET Core templates, the framework registers more than 250 services.
The following table lists a small sample of these framework-registered services:
ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.
For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core .
For information on using dependency injection in applications other than web apps, see Dependency injection in .NET .
For more information on dependency injection of options, see Options pattern in ASP.NET Core .
This topic provides information on dependency injection in ASP.NET Core. The primary documentation on using dependency injection is contained in Dependency injection in .NET .
A dependency is an object that another object depends on. Examine the following MyDependency class with a WriteMessage method that other classes depend on:
A class can create an instance of the MyDependency class to make use of its WriteMessage method. In the following example, the MyDependency class is a dependency of the IndexModel class:
The class creates and directly depends on the MyDependency class. Code dependencies, such as in the previous example, are problematic and should be avoided for the following reasons:
Dependency injection addresses these problems through:
In the sample app , the IMyDependency interface defines the WriteMessage method:
This interface is implemented by a concrete type, MyDependency :
The sample app registers the IMyDependency service with the concrete type MyDependency . The AddScoped method registers the service with a scoped lifetime, the lifetime of a single request. Service lifetimes are described later in this topic.
In the sample app, the IMyDependency service is requested and used to call the WriteMessage method:
By using the DI pattern, the controller:
The implementation of the IMyDependency interface can be improved by using the built-in logging API:
The updated ConfigureServices method registers the new IMyDependency implementation:
MyDependency2 depends on ILogger , which it requests in the constructor. ILogger is a framework-provided service .
It's not unusual to use dependency injection in a chained fashion. Each requested dependency in turn requests its own dependencies. The container resolves the dependencies in the graph and returns the fully resolved service. The collective set of dependencies that must be resolved is typically referred to as a dependency tree , dependency graph , or object graph .
The container resolves ILogger by taking advantage of (generic) open types , eliminating the need to register every (generic) constructed type .
In dependency injection terminology, a service:
The framework provides a robust logging system. The IMyDependency implementations shown in the preceding examples were written to demonstrate basic DI, not to implement logging. Most apps shouldn't need to write loggers. The following code demonstrates using the default logging, which doesn't require any services to be registered in ConfigureServices :
Using the preceding code, there is no need to update ConfigureServices , because logging is provided by the framework.
Services can be injected into the Startup constructor and the Startup.Configure method.
Only the following services can be injected into the Startup constructor when using the Generic Host ( IHostBuilder ):
Any service registered with the DI container can be injected into the Startup.Configure method:
The ASP.NET Core framework uses a convention for registering a group of related services. The convention is to use a single Add{GROUP_NAME} extension method to register all of the services required by a framework feature. For example, the AddControllers extension method registers the services required for MVC controllers.
The following code is generated by the Razor Pages template using individual user accounts and shows how to add additional services to the container using the extension methods AddDbContext and AddDefaultIdentity :
Consider the following ConfigureServices method, which registers services and configures options:
Related groups of registrations can be moved to an extension method to register services. For example, the configuration services are added to the following class:
The remaining services are registered in a similar class. The following ConfigureServices method uses the new extension methods to register the services:
Note: Each services.Add{GROUP_NAME} extension method adds and potentially configures services. For example, AddControllersWithViews adds the services MVC controllers with views require, and AddRazorPages adds the services Razor Pages requires. We recommended that apps follow the naming convention of creating extension methods in the Microsoft.Extensions.DependencyInjection namespace. Creating extension methods in the Microsoft.Extensions.DependencyInjection namespace:
To use scoped services in middleware, use one of the following approaches:
It's common to use multiple implementations when mocking types for testing .
Registering a service with only an implementation type is equivalent to registering that service with the same implementation and service type. This is why multiple implementations of a service cannot be registered using the methods that don't take an explicit service type. These methods can register multiple instances of a service, but they will all have the same implementation type.
Any of the above service registration methods can be used to register multiple service instances of the same service type. In the following example, AddSingleton is called twice with IMyDependency as the service type. The second call to AddSingleton overrides the previous one when resolved as IMyDependency and adds to the previous one when multiple services are resolved via IEnumerable . Services appear in the order they were registered when resolved via IEnumerable<{SERVICE}> .
By default, Entity Framework contexts are added to the service container using the scoped lifetime because web app database operations are normally scoped to the client request. To use a different lifetime, specify the lifetime by using an AddDbContext overload. Services of a given lifetime shouldn't use a database context with a lifetime that's shorter than the service's lifetime.
To demonstrate the difference between service lifetimes and their registration options, consider the following interfaces that represent a task as an operation with an identifier, OperationId . Depending on how the lifetime of an operation's service is configured for the following interfaces, the container provides either the same or different instances of the service when requested by a class:
The following Operation class implements all of the preceding interfaces. The Operation constructor generates a GUID and stores the last 4 characters in the OperationId property:
The Startup.ConfigureServices method creates multiple registrations of the Operation class according to the named lifetimes:
The sample app demonstrates object lifetimes both within and between requests. The IndexModel and the middleware request each kind of IOperation type and log the OperationId for each:
Similar to the IndexModel , the middleware resolves the same services:
Scoped services must be resolved in the InvokeAsync method:
To reduce the logging output, set "Logging:LogLevel:Microsoft:Error" in the appsettings.Development.json file:
Create an IServiceScope with IServiceScopeFactory.CreateScope to resolve a scoped service within the app's scope. This approach is useful to access a scoped service at startup to run initialization tasks.
The following example shows how to access the scoped IMyDependency service and call its WriteMessage method in Program.Main :
For more information, see Scope validation .
Services and their dependencies within an ASP.NET Core request are exposed through HttpContext.RequestServices .
The framework creates a scope per request, and RequestServices exposes the scoped service provider. All scoped services are valid for as long as the request is active.
Prefer requesting dependencies as constructor parameters over reso
Adorable Masturbating
Overwatch Comics
Bi Sex Oral