Open
Description
Description
DI does not respect unmanaged
constraint and enables instantiation of invalid types.
Reproduction Steps
Run the code.
using Microsoft.Extensions.DependencyInjection;
using var provider = new ServiceCollection()
.AddSingleton(typeof(IGeneralInterface<>), typeof(UnmanagedConstrainedImplementation<>))
.BuildServiceProvider();
var invalid = provider.GetRequiredService<IGeneralInterface<Managed>>();
invalid.Call(new());
public interface IGeneralInterface<T>
{
void Call(T value);
}
public class UnmanagedConstrainedImplementation<T>
: IGeneralInterface<T>
where T : unmanaged
{
public void Call(T value)
{
}
}
public record struct Managed(object One, object Other);
Expected behavior
Exception is thrown.
Actual behavior
The program successfully completes.
Regression?
No, as far as I know.
Known Workarounds
Wrap instantiation in a factory, get modreq
modifications by reflection and check by hand.
Configuration
Not specific to configuration.
Other information
IMHO, it is up to debate whether System.RuntimeType.MakeGenericType
should respect the constraint, and I tend to believe it should, but the DI is meant to be used by C# end-users and definitely should not instantiate types which are invalid for the language.