Skip to content

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

Closed

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

Activity

  1. ghost added
    untriaged
    on Dec 23, 2022
  2. schwarzr commented on Dec 23, 2022

    @schwarzr
    Author

    area-Extensions-DependencyInjection

  3. added
    help wanted
    and removed
    untriaged
    on Jan 5, 2023
  4. added this to the 8.0.0 milestone on Jan 5, 2023
  5. madelson commented on Jan 8, 2023

    @madelson
    Contributor

    I'd be interested in working on this.

    It would be helpful to confirm my understanding of the precise desired behavior in cases like this, though. Trying to piece together the intent from the code:

    • Open generic registrations are always "lower precedence" than exact registrations.
    • The default IEnumerable registration is always "lower precedence" than open generic registrations.
    • Among otherwise equal registrations, earlier registrations are "lower precedence" than exact registrations.
    • When resolving the default IEnumerable registration, registrations are returned in order from lowest precedence to highest precedence.

    Is that all correct?

  6. davidfowl commented on Jan 8, 2023

    @davidfowl
    Member

    I believe it's the same issue as this #68053. We should confirm though, it only happens when the environment is development right?

  7. madelson commented on Jan 8, 2023

    @madelson
    Contributor

    I believe it's the same issue as this #68053

    @davidfowl that seems right; potentially the fix there did not fully resolve the problem.

    I believe it's the same issue as this #68053. We should confirm though, it only happens when the environment is development right?

    @schwarzr should confirm, but from my repro the code shown requires development environment because in that setup it is being triggered by ValidateOnBuild = true in the ServiceProviderOptions.

    However, ValidateOnBuild is not the only way to trigger this. For example the following also repros for me:

    void Main()
    {
    	var sc = new ServiceCollection();
    	sc.AddTransient<IProcessor<string>, SampleProcessor>();
    	sc.AddTransient(typeof(IProcessor<>), typeof(GenericProcessor<>));
    	
            // not using build validation
            using var s = sc.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = false });
            s.GetService(typeof(IProcessor<string>)); // resolve this first: gives SampleProcessor
    	s.GetServices<IProcessor<string>>(); // now this gives [SampleProcessor, SampleProcessor]
    }
    
    public interface IProcessor<T> { }
    
    public class SampleProcessor : IProcessor<string> { }
    
    public class GenericProcessor<T> : IProcessor<T> { }
    
  8. davidfowl commented on Jan 8, 2023

    @davidfowl
    Member

    However, ValidateOnBuild is not the only way to trigger this. For example the following also repros for me:

    That raises the priority of this. This was assumed to only be broken in validation scenarios.

  9. schwarzr commented on Jan 8, 2023

    @schwarzr
    Author

    @madelson

    @schwarzr should confirm, but from my repro the code shown requires development environment because in that setup it is being triggered by ValidateOnBuild = true in the ServiceProviderOptions.

    I have been able to reproduce this issue outside Visual Studio and without ValidateOnBuild = true. So no, i don't think it is limited do the development environment.

    @davidfowl
    One thing i recognized when i investigated this issue is, that if you register the generic version twice the resulting instances are: [SampleProcessor, GenericProcessor, SampleProcessor]

    void Main()
    {
    	var sc = new ServiceCollection();
    	sc.AddTransient<IProcessor<string>, SampleProcessor>();
    	sc.AddTransient(typeof(IProcessor<>), typeof(GenericProcessor<>));
    	sc.AddTransient(typeof(IProcessor<>), typeof(GenericProcessor<>));
    	
            // not using build validation
            using var s = sc.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = false });
            s.GetService(typeof(IProcessor<string>)); // resolve this first: gives SampleProcessor
    	s.GetServices<IProcessor<string>>(); // now this gives [SampleProcessor, GenericProcessor, SampleProcessor]
    }
    
    public interface IProcessor<T> { }
    
    public class SampleProcessor : IProcessor<string> { }
    
    public class GenericProcessor<T> : IProcessor<T> { }

    and if you register the generic service first, it kind of works as expected.

    void Main()
    {
    	var sc = new ServiceCollection();
    	sc.AddTransient(typeof(IProcessor<>), typeof(GenericProcessor<>));
    	sc.AddTransient<IProcessor<string>, SampleProcessor>();
    
            // not using build validation
            using var s = sc.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = false });
            s.GetService(typeof(IProcessor<string>)); // resolve this first: gives SampleProcessor
    	s.GetServices<IProcessor<string>>(); // now this gives [GenericProcessor, SampleProcessor]
    }
    
    public interface IProcessor<T> { }
    
    public class SampleProcessor : IProcessor<string> { }
    
    public class GenericProcessor<T> : IProcessor<T> { }
  10. added a commit that references this issue on Jan 10, 2023
    22dd1ea
  11. ghost added
    in-pr
    on Jan 10, 2023
  12. steveharter commented on Jun 8, 2023

    @steveharter
    Contributor

    Are there any requests to backport the fix to v7 and possible v6 (since it's LTS)?

  13. ghost removed
    in-pr
    on Jun 9, 2023
  14. ghost locked as resolved and limited conversation to collaborators on Jul 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Extensions-DependencyInjectionbughelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions