Skip to content

Verify null-safety of generic type parameters #1017

@rpmrmartin

Description

@rpmrmartin

In the example below, I have a class with a dependency on a generic interface with a non-nullable type parameter and a class implementing that interface with the same type parameter, but nullable. If I use pure DI to build the object graph, I get a compiler warning about the difference in nullability. However, if I use SimpleInjector to build the object graph, I don't get any warnings at compile time or runtime, leading to possible NullReferenceExceptions in the consumer class when its dependency returns a null that the consumer is not expecting. I would like SimpleInjector to warn me that an implementation of IService<string?> cannot be injected into a consumer expecting IService<string> (given that the type parameter T is not contravariant).

using SimpleInjector;

using var container = new Container();

container.Register<IService<string?>, Service>();
container.Register<Consumer>();

/*
    CS8620 Argument of type 'Service' cannot be used for parameter 'service' of type
    'IService<string>' in 'Consumer.Consumer(IService<string> service)' due to differences in the
    nullability of reference types.
*/
_ = new Consumer(new Service());

// No error
container.Verify();
_ = container.GetInstance<Consumer>();

interface IService<T> { }

class Service : IService<string?> { }

internal class Consumer
{
    public Consumer(IService<string> service) { }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions