根据文档,我们可以将以下服务注入启动类:
但是我们也可以使用方法注入来解决方法中的这些服务Configure()
:
可以在Configure方法签名中指定其他服务,例如IWebHostEnvironment,ILoggerFactory或ConfigureServices中定义的任何服务。这些服务(如果可用)将被注入。
我使用哪种注射变体会有所不同吗?
具体来说,IWebHostEnvironment
在构造函数中解析然后Configure()
通过私有字段在方法中进行访问与将其作为方法参数注入有区别吗?
public class Startup
{
private readonly IWebHostEnvironment env;
public Startup(IWebHostEnvironment env)
{
this.env = env;
}
public void Configure(IApplicationBuilder app)
{
if (this.env.IsDevelopment())
[...]
}
}
与
public class Startup
{
public Startup() {}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
[...]
}
}
一般而言,构造函数和方法DI可以是基于使用此框架但不使用其他框架的某个框架的偏好或要求。在asp.net core
(以及.net core
通常情况下)中,建议使用构造函数注入,因为它可以清楚地说明依赖项。这比方法注入更有意义。但是,在某些情况下,您必须使用方法注入,因为依赖项只能在调用时可用方法或至少在构建类/服务时不可用。有时,注入的服务仅用于特定的方法调用,在这种情况下,将使用方法注入。在某些情况下,服务实例是单例的,但其方法调用需要某些作用域服务,因此将使用方法注入。该场景的一个示例是使用convention-based middleware
。基于约定的中间件是单件的,在应用程序启动时创建一次,而不是针对每个请求。因此,所有作用域服务都必须注入Invoke
orInvokeAsync
方法中。但是,基于工厂的中间件可以将其范围内的服务注入到构造函数中,因为它们可以按请求创建(注册为范围内或临时的)。
就像Startup
上课一样。您可以将一些内置服务注入Startup
的构造函数中,如IConfiguration
,,IWebHostEnvironment
...。通常,很多可用的服务(之前注册)ConfigureServices
都可以注入Startup
的构造函数中。这意味着所有注册的服务ConfigureServices
均不可注入Startup
的构造函数。但是,您可以将所有注册的服务(包括内置服务和您自己的服务)注入该方法中Configure
。请注意,注入的服务Configure
应该是单例的和瞬态的,对于作用域服务,使用它们时可能会出现问题。这实际上取决于您使用的特定服务。
以下示例显示了ConfigureServices
无法将自己的服务(在中注册)注入Startup
的构造函数中:
public interface ISomeService {}
public class SomeService : ISomeService {}
public class Startup {
//will not work because at this time, the ISomeService has not been registered yet
public Startup(ISomeService someService){
//an error will be thrown complaining about not being able to
//resolve the ISomeService
}
public void ConfigureServices(IServiceCollection services){
//...
services.AddSingleton<ISomeService,SomeService>();
//...
}
//this works because at this time the ConfigureServices was called
//the services container has been built with your registered ISomeService
public void Configure(IApplicationBuilder app, ISomeService someService){
//...
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句