What does „services.Add(new ServiceDescriptor ...“ do ?
For detail information about services.Add
, you could refer the source code 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;
}
For this code, it add the ServiceDescriptor
to the ServiceCollection
.
What is a ServiceDescriptor ?
ServiceDescriptor
describes a service with its service type, implementation, and lifetime. It will be used to initializes a new instance of ServiceDescriptor with the specified implementationType.
By debugging the code, I see that SQLConnectionFactory is only instantiated once. Does the call "services.Add" (always) create a singleton object? If so what is the difference to services.AddSingleton?
This depends on whehter you pass the scope for services.Add
. The default scope for services.add
is ServiceLifetime
. You could descipe the service with different scope by passing ServiceLifetime
like services.Add(new ServiceDescriptor(typeof(ISQLConnectionFactory), new SQLConnectionFactory(GetConnectionString("DefaultConnection")), ServiceLifetime.Scoped));
There is no different between services.Add
and AddSingleton
. The AddSingleton
just call services.Add
with passing 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);
}