-2

What is the difference between injecting a service using services.(AddScoped, AddTransient, AddSingleton) and the service.replace for example

services.AddScoped<IPasswordHasher<ApplicationUser>, SqlPasswordHasher<ApplicationUser>>();
services.Replace(new ServiceDescriptor(
    serviceType: typeof(IPasswordHasher<ApplicationUser>),
    implementationType: typeof(SqlPasswordHasher<ApplicationUser>),
        ServiceLifetime.Scoped));
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49
  • 1
    Well, `Replace()` will _replace_ any previously registered service of that service type, so if there was one already registered it would be removed. `Add()` _adds_ another one, so if there was one there before, there'd now be two. – Martin Costello Jul 13 '21 at 10:45
  • There is already an answer. Please search before asking a new question. https://stackoverflow.com/questions/38138100/addtransient-addscoped-and-addsingleton-services-differences – Ibrahim ULUDAG Jul 13 '21 at 10:47
  • @İbrahimULUDAĞ My question is highly different i am asking the difference between service.add and service.replace actually not the types in add, Please read the question carefully before commenting. – Mohamed Tawheed Jul 13 '21 at 11:31

1 Answers1

0

The difference can be seen in the source code.

The first one is the IServiceCollection interface, a core interface of the dependency injection.

public interface IServiceCollection : IList<ServiceDescriptor>
{
}

IServiceCollection is just a list of ServiceDescriptor objects. ServiceDescriptor describes the information of the injected types.

Based on this interface, the two methods Add and Replace can be discussed.

public static IServiceCollection Add(
            this IServiceCollection collection,
            ServiceDescriptor descriptor)
{
    ...
    collection.Add(descriptor);
    return collection;
}

public static IServiceCollection Replace(
            this IServiceCollection collection,
            ServiceDescriptor descriptor)
{
    ...
    // Remove existing
    int count = collection.Count;
    for (int i = 0; i < count; i++)
    {
        if (collection[i].ServiceType == descriptor.ServiceType)
        {
            collection.RemoveAt(i);
            break;
        }
    }
    collection.Add(descriptor);
    return collection;
}

Add just pushes the service descriptor into the list, while Replace firstly checks and deletes the descriptors in the list with the same service type, and finally add the current descriptor to the list.

Therefore, the time complexities of these two methods are different. The time complexity of Add in most cases is O(1), while Replace is O(n) (traverse the list). However, Add does not guarantee that the added descriptor is unique, but Replace will delete the descriptors with the same service type and add the current one.

iskcal
  • 52
  • 3