zl程序教程

您现在的位置是:首页 >  其他

当前栏目

小谈startup类ConfigureServices方法的作用

2023-03-20 14:53:00 时间

这个是我在面试中遇到的一道面试题,记录下来分享给大家。 简单说ConfigureServices是配置服务器的DI容器,可以添加一些服务进到依赖注入容器中。具体来说就是把中间件等添加到DI容器中,最后都是添加到IServiceCollection中,比如下面的代码:

 services.AddIdentityServer()
		.AddDeveloperSigningCredential()
		.AddInMemoryApiResources(Config.GetResource())
		.AddInMemoryClients(Config.GetClients())
		.AddTestUsers(Config.GetTestUsers())
		.AddProfileService<ProfileService>()
		.AddResourceOwnerValidator<LoginValidator>();

对于.AddProfileService()来说它已经内置了一个默认实现IProfileService接口的类,默认注入内置的DefaultProfileServer。其实里面的实现是当遇到IProfileService实例化成自定义类ProfileService,而不使用内置的。ASP.NET Core依赖注入在应用程序启动时提供服务。我们可以通过在Startup类的构造方法或Configure方法中包含适当的接口作为参数来请求这些服务。ConfigureServices方法只能接受IServiceCollection参数,但是可以从这个集合中检索任何已注册的服务,因此不需要额外参数。下面由启动方法请求的服务:

位置

服务

构造方法中

IHostingEnvironment,ILogger

ConfigureServices方法中

IServiceCollection

Configure方法中

IApplicationBuilder, IHostingEnvironment, ILoggerFactory

Startup类构造方法或Configure方法可以请求由WebHostBuilde ConfigureServices方法添加的任何服务。使用WebHostBuilder在启动方法中提供需要的任何服务。