Reputation: 3089
I am working on an existing WebAPI project and inside
public void ConfigureServices(IServiceCollection services)
the IoC container is setup like so
services.Add(new ServiceDescriptor(typeof(ISQLConnectionFactory), new SQLConnectionFactory(GetConnectionString("DefaultConnection"))));
(there are also lots of services.AddScoped which I'm not asking about)
Questions
or perhaps someone can provide some insight
Upvotes: 5
Views: 2820
Reputation: 29976
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);
}
Upvotes: 5
Reputation: 26
This link could provide some explanations https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2
services.Add(
adds new dependency registration that later can be resolvednew ServiceDescriptor
constructor provide explicit registration with the factory that will supply new instances and lifetime descriptionservices.AddSingleton
is just a shorthand for doing this with a defined lifetime as Singleton Upvotes: 0