Manually parse ASP.NET Core service in ConfigureServices
The
method in ASP.NET Core used to configure dependency injection containers does not provide a method for directly parsing services. To manually parse the service from this method, an alternative method is required.
Service Provider Mode
To parse services, ASP.NET Core uses the service provider pattern. After the service collection is built, it is converted to anIServiceProvider instance, allowing the service to be parsed.
Injection service provider] One way to parse a service is to inject the
IServiceProvider instance into the constructor of the Startup
class. However, this approach provides only access to the limited necessary services injected by the hosting layer.
] In the
Configure method, the IApplicationBuilder
provides the ApplicationServices
property, which contains a service provider that can access all registered services.
public void Configure(IApplicationBuilder app)
{
var serviceProvider = app.ApplicationServices;
var fooService = serviceProvider.GetService();
}
Build intermediate service provider] To parse a service in the
ConfigureServices method, you can build an intermediate service provider from a partially built collection of services. However, this only includes services registered before this.
public void Configure(IApplicationBuilder app)
{
var serviceProvider = app.ApplicationServices;
var fooService = serviceProvider.GetService();
}
Avoid manual parsing] Manual parsing services is not usually recommended because it violates the dependency injection principle. Instead, use injection or utilize the service provider injection in the
Configure method.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3