Skip to content

Commit

Permalink
Added "AddDataLoader<TService, TImplementation>" overload that takes …
Browse files Browse the repository at this point in the history
…a factory (#7674)
  • Loading branch information
danielreynolds1 authored and michaelstaib committed Nov 29, 2024
1 parent a390e46 commit 09211ff
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,19 @@ public static IServiceCollection AddDataLoader<T>(
return services;
}

public static IServiceCollection AddDataLoader<TService, TImplementation>(
this IServiceCollection services,
Func<IServiceProvider, TImplementation> factory)
where TService : class, IDataLoader
where TImplementation : class, TService
{
services.TryAddDataLoaderCore();
services.AddSingleton(new DataLoaderRegistration(typeof(TService), typeof(TImplementation), sp => factory(sp)));
services.TryAddScoped<TImplementation>(sp => sp.GetDataLoader<TImplementation>());
services.TryAddScoped<TService>(sp => sp.GetDataLoader<TService>());
return services;
}

public static IServiceCollection TryAddDataLoaderCore(
this IServiceCollection services)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using GreenDonut;
using Xunit;
using static GreenDonut.TestHelpers;

namespace Microsoft.Extensions.DependencyInjection;

public class DataLoaderServiceCollectionExtensionsTests
{
[Fact]
public void ImplFactoryIsCalledWhenServiceIsResolved()
{
// arrange
var factoryCalled = false;
var fetch = CreateFetch<string, string>();
var services = new ServiceCollection()
.AddScoped<IBatchScheduler, ManualBatchScheduler>()
.AddDataLoader(sp =>
{
factoryCalled = true;
return new DataLoader<string, string>(fetch, sp.GetRequiredService<IBatchScheduler>());
});
var scope = services.BuildServiceProvider().CreateScope();

// act
var dataLoader = scope.ServiceProvider.GetRequiredService<DataLoader<string, string>>();

// assert
Assert.NotNull(dataLoader);
Assert.True(factoryCalled);
}

[Fact]
public void InterfaceImplFactoryIsCalledWhenServiceIsResolved()
{
// arrange
var factoryCalled = false;
var fetch = CreateFetch<string, string>();
var services = new ServiceCollection()
.AddScoped<IBatchScheduler, ManualBatchScheduler>()
.AddDataLoader<IDataLoader<string, string>, DataLoader<string, string>>(sp =>
{
factoryCalled = true;
return new DataLoader<string, string>(fetch, sp.GetRequiredService<IBatchScheduler>());
});
var scope = services.BuildServiceProvider().CreateScope();

// act
var dataLoader = scope.ServiceProvider.GetRequiredService<DataLoader<string, string>>();
var asInterface = scope.ServiceProvider.GetRequiredService<IDataLoader<string, string>>();

// assert
Assert.NotNull(dataLoader);
Assert.NotNull(asInterface);
Assert.True(factoryCalled);
}
}

0 comments on commit 09211ff

Please sign in to comment.