Skip to content
This repository has been archived by the owner on Nov 2, 2018. It is now read-only.

Commit

Permalink
Add RemoveAll extension method to service collection (#539)
Browse files Browse the repository at this point in the history
  • Loading branch information
pakrym authored Jun 30, 2017
1 parent 3591c0f commit 62d92c8
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -540,5 +540,40 @@ public static IServiceCollection Replace(
collection.Add(descriptor);
return collection;
}

/// <summary>
/// Removes all services of type <typeparamef name="T"/> in <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <returns></returns>
public static IServiceCollection RemoveAll<T>(this IServiceCollection collection)
{
return RemoveAll(collection, typeof(T));
}

/// <summary>
/// Removes all services of type <paramef name="serviceType"/> in <see cref="IServiceCollection"/>.
/// </summary>
/// <param name="collection">The <see cref="IServiceCollection"/>.</param>
/// <param name="serviceType">The service type to remove.</param>
/// <returns></returns>
public static IServiceCollection RemoveAll(this IServiceCollection collection, Type serviceType)
{
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}

for (var i = collection.Count - 1; i >= 0; i--)
{
var descriptor = collection[i];
if (descriptor.ServiceType == serviceType)
{
collection.RemoveAt(i);
}
}

return collection;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -395,5 +395,24 @@ public void Replace_ReplacesFirstServiceWithMatchingServiceType()
// Assert
Assert.Equal(new[] { descriptor2, descriptor3 }, collection);
}

[Fact]
public void RemoveAll_RemovesAllServicesWithMatchingServiceType()
{
// Arrange
var descriptor = new ServiceDescriptor(typeof(IFakeServiceInstance), typeof(FakeService), ServiceLifetime.Transient);
var collection = new ServiceCollection
{
descriptor,
new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient),
new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient)
};

// Act
collection.RemoveAll<IFakeService>();

// Assert
Assert.Equal(new[] { descriptor }, collection);
}
}
}

0 comments on commit 62d92c8

Please sign in to comment.