我正在一个现有的WebAPI项目中以及内部
public void ConfigureServices(IServiceCollection services)
IoC容器的设置如下
services.Add(new ServiceDescriptor(typeof(ISQLConnectionFactory), new SQLConnectionFactory(GetConnectionString("DefaultConnection"))));
(也有很多服务。我不问这些问题。AddScoped)
问题
或者也许有人可以提供一些见识
答案 0 :(得分:1)
“ services.Add(new ServiceDescriptor ...”起什么作用?
有关services.Add
的详细信息,您可以参考源代码Add。
public static IServiceCollection Add(
this IServiceCollection collection,
ServiceDescriptor descriptor)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
if (descriptor == null)
{
throw new ArgumentNullException(nameof(descriptor));
}
collection.Add(descriptor);
return collection;
}
对于此代码,它将ServiceDescriptor
添加到ServiceCollection
。
什么是ServiceDescriptor?
ServiceDescriptor
描述了服务及其服务类型,实现和生存期。它将用于使用指定的ImplementationType初始化ServiceDescriptor的新实例。
通过调试代码,我看到SQLConnectionFactory仅实例化一次。调用“ services.Add”(总是)是否创建一个单例对象?如果是这样,services.AddSingleton有什么区别?
这取决于您为services.Add
传递范围的情况。 services.add
的默认范围是ServiceLifetime
。您可以通过传递ServiceLifetime
之类的services.Add(new ServiceDescriptor(typeof(ISQLConnectionFactory), new SQLConnectionFactory(GetConnectionString("DefaultConnection")), ServiceLifetime.Scoped));
来描述具有不同范围的服务
services.Add
和AddSingleton
之间没有区别。 AddSingleton
只需调用services.Add
并传递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);
}
答案 1 :(得分:0)
此链接可以提供一些解释 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2
services.Add(
添加了新的依赖项注册,以后可以解决new ServiceDescriptor
constructor向工厂提供了明确的注册,该工厂将提供新的实例和生命周期描述services.AddSingleton
只是这样做的简写,定义的生存期为Singleton