Skip to content

Commit

Permalink
Check if service is keyed before accessing ImplementationType
Browse files Browse the repository at this point in the history
  • Loading branch information
psampaio authored and jeremydmiller committed May 10, 2024
1 parent 29ee873 commit 66ea497
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Collections.Generic;
using Lamar.Microsoft.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Shouldly;
using Xunit;

namespace Lamar.AspNetCoreTests.Bugs;

public class Bug_395_keyed_service_closed_generic_interface_registration_check
{
class ClassA {}

interface IGenericService<T> {}

class ServiceA : IGenericService<ClassA> {}

[Fact]
public void do_not_blow_up()
{
var serviceName = "MyServiceName";

var builder = new HostBuilder()
.ConfigureServices((context, services) =>
{
// This is needed because of https://github.com/aspnet/Logging/issues/691
services.AddSingleton<ILoggerFactory, LoggerFactory>(sp =>
new LoggerFactory(
sp.GetRequiredService<IEnumerable<ILoggerProvider>>(),
sp.GetRequiredService<IOptionsMonitor<LoggerFilterOptions>>()
)
);
services.AddKeyedTransient<IGenericService<ClassA>, ServiceA>(serviceName);
})
.UseLamar();

using (var host = builder.Start())
{
var container = host.Services.ShouldBeOfType<Container>();

container.GetInstance<IGenericService<ClassA>>()
.ShouldNotBeNull();
}
}
}
4 changes: 3 additions & 1 deletion src/Lamar/ServiceGraph.cs
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,9 @@ private ServiceFamily buildFamilyForInstanceGroup(IServiceCollection services,

private ServiceFamily buildClosedGenericType(Type serviceType, IServiceCollection services)
{
var closed = services.Where(x => x.ServiceType == serviceType && !x.ImplementationType.IsOpenGeneric())
var closed = services.Where(x => x.ServiceType == serviceType && (x.IsKeyedService
? !x.KeyedImplementationType.IsOpenGeneric()
: !x.ImplementationType.IsOpenGeneric()))
.Select(Instance.For);

var templated = services
Expand Down

0 comments on commit 66ea497

Please sign in to comment.