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

Resolving interfaces with contravariant type parameter fails with RegisteringImplementationNotAssignableToServiceType error #432

Closed
PhilippK13 opened this issue Oct 20, 2021 · 1 comment
Assignees
Labels
bug Something isn't working
Milestone

Comments

@PhilippK13
Copy link

PhilippK13 commented Oct 20, 2021

Hi.

I have the following hierarchy(simplified for brevity):

public class Settings
{
  public string Address {get; set;}
}

public class ExtraSettings : Settings
{
  public string Key {get; set;}
}

public interface IValidator<in T>
{
  public bool IsValid(T settings);
}

public abstract class AbstractValidator<T> : IValidator<T>
{
  public bool IsValid(T settings)
  {
    return true;
  }
}

public class SettingsValidator : AbstractValidator<Settings>
{
  
}

I'm trying to make this to work, but getting a RegisteringImplementationNotAssignableToServiceType error:

var genericType = typeof(IValidator<>).MakeGenericType(typeof(ExtraSettings));
var services = new ServiceCollection(); // Microsoft.Extensions.DependencyInjection

services.AddSingleton<IValidator<ExtraSettings>, SettingsValidator>();
  
var container = new Container();
var adaptedContainer = container.WithDependencyInjectionAdapter(services); // this throws
IServiceProvider serviceProvider = adaptedContainer;

var validator = serviceProvider.GetService(type);

The following is the message of the exceptin throw:
code: Error.RegisteringImplementationNotAssignableToServiceType; message: Registering implementation type SettingsValidator is not assignable to service type IValidator<ExtraSettings>.

However, this code(without DryIoC) works as expected:

var genericType = typeof(IValidator<>).MakeGenericType(typeof(ExtraSettings));
var services = new ServiceCollection(); // Microsoft.Extensions.DependencyInjection

services.AddSingleton<IValidator<ExtraSettings>, SettingsValidator>();

var serviceProvider = services.BuildServiceProvider();
var validator = serviceProvider.GetService(type);

I don't think I'm violating any Type rules, so I expect the DryIoC to work just fine. Is this a bug or am I missing something?

@dadhi
Copy link
Owner

dadhi commented Oct 20, 2021

@PhilippK13 Thanks for reporting and code repro.
It seems that I have already fixed the problem in context of the #418 . But I did not release the fix yet. Hoping to release Today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants