C# 微软在哪里';添加(新的ServiceDescriptor(…)?
我在一个现有的WebAPI项目和内部工作C# 微软在哪里';添加(新的ServiceDescriptor(…)?,c#,inversion-of-control,asp.net-core-webapi,C#,Inversion Of Control,Asp.net Core Webapi,我在一个现有的WebAPI项目和内部工作 public void ConfigureServices(IServiceCollection services) IoC容器是这样设置的 services.Add(new ServiceDescriptor(typeof(ISQLConnectionFactory), new SQLConnectionFactory(GetConnectionString("DefaultConnection")))); (还有很多服务。AddScoped,我不
public void ConfigureServices(IServiceCollection services)
IoC容器是这样设置的
services.Add(new ServiceDescriptor(typeof(ISQLConnectionFactory), new SQLConnectionFactory(GetConnectionString("DefaultConnection"))));
(还有很多服务。AddScoped,我不想问)
问题
这个链接可以提供一些解释
添加新的依赖项注册,以后可以解决此问题services.Add(
提供工厂的明确注册,工厂将提供新实例和生存期描述new ServiceDescriptor
只是将生命周期定义为services.AddSingleton
服务的详细信息,请参见源代码
对于此代码,它将服务描述符
添加到服务集合
什么是服务描述符
ServiceDescriptor
描述服务及其服务类型、实现和生存期。它将用于使用指定的实现类型初始化ServiceDescriptor的新实例
通过调试代码,我看到SQLConnectionFactory只实例化了一次。调用“services.Add”(总是)是否创建了一个singleton对象?如果是,那么services.AddSingleton的区别是什么
这取决于您是否传递服务的作用域。添加。服务的默认作用域。添加的默认作用域是服务生命周期。您可以通过传递服务生命周期类似服务来描述具有不同作用域的服务。添加(新的服务描述符(类型)(ISQLConnectionFactory),新的SQLConnectionFactory(GetConnectionString(“DefaultConnection”)),ServiceLifetime.Scoped);
服务之间没有区别。Add
和AddSingleton
。AddSingleton
只需调用服务。Add
通过传递服务生命周期。Singleton
public static IServiceCollection AddSingleton(
this IServiceCollection services,
Type serviceType,
Type implementationType)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}
if (implementationType == null)
{
throw new ArgumentNullException(nameof(implementationType));
}
return Add(services, serviceType, implementationType, ServiceLifetime.Singleton);
}
public static IServiceCollection AddSingleton(
this IServiceCollection services,
Type serviceType,
Type implementationType)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}
if (implementationType == null)
{
throw new ArgumentNullException(nameof(implementationType));
}
return Add(services, serviceType, implementationType, ServiceLifetime.Singleton);
}