Skip to content

Injected service is of wrong type when registered multiple times with generic registration - Microsoft.Extensions.DependecyInjection #79938

@schwarzr

Description

@schwarzr

Description

When registring a service in the IServiceCollection of asp.net core >= 6.0 once with a concrete type and once as a generic registration you get the wrong types of instances from the ServiceProvider.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddTransient<IProcessor<SampleEntity>, SampleEntityProcessor>();
builder.Services.AddTransient(typeof(IProcessor<>), typeof(GenericProcessor<>));

var app = builder.Build();

// two instances of type SampleEntityProcessor are produced;
var processors = app.Services.GetServices<IProcessor<SampleEntity>>();

app.Run();

Reproduction Steps

Create a new asp.net core 6 Project:

Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddTransient<IProcessor<SampleEntity>, SampleEntityProcessor>();
builder.Services.AddTransient(typeof(IProcessor<>), typeof(GenericProcessor<>));

var app = builder.Build();

// two instances of type SampleEntityProcessor are produced;
var processors = app.Services.GetServices<IProcessor<SampleEntity>>();

app.Run();

IProcessor

public interface IProcessor<T>
    where T : class
{
    Task ProcessAsync();
}

GenericProcessor

public class GenericProcessor<T> : IProcessor<T>
    where T : class
{
    public Task ProcessAsync()
    {
        return Task.CompletedTask;
    }
}

SampleEntity

public class SampleEntity
{
    public int Id { get; set; }

    public string Name { get; set; }
}

SampleEntityProcessor

public class SampleEntityProcessor : IProcessor<SampleEntity>
{
    public Task ProcessAsync()
    {
        return Task.CompletedTask;
    }
}

Expected behavior

var processors = app.Services.GetServices<IProcessor<SampleEntity>>();

should return

  • instance of SampleEntityProcessor
  • instance of GenericProcessor

Actual behavior

var processors = app.Services.GetServices<IProcessor<SampleEntity>>();

currently returns

  • instance of SampleEntityProcessor
  • instance of SampleEntityProcessor

Screenshot 2022-12-23 184811

Regression?

Tested with:

  • asp.net 3.1 -> OK
  • asp.net 5 -> OK
  • asp.net 6 -> Failed (6.0.12)
  • asp.net 7 -> Failed (7.0.1)

Known Workarounds

No response

Configuration

Windows 11 x64
.net runtime 6.0.12
.net runtime 7.0.1
Visual Studio 2022

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions