Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check if service is keyed before accessing ImplementationType #396

Merged
merged 1 commit into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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