Skip to content

Unity GetService for Struct Type with a default constructor calls the constructor #87

@eerhardt

Description

@eerhardt

I'm adding a test for dotnet/runtime#47722. In doing so, I created a Struct type that has a default constructor (note you can only do this in IL today, until dotnet/csharplang#99 is implemented).

Calling ActivatorUtilities.CreateInstance(provider, typeof(ClassWithOptionalArgsCtorWithStructs)) for a class whose constructor is defined like the following:

public struct StructWithPublicDefaultConstructor
{
    public readonly bool ConstructorInvoked;

    public StructWithPublicDefaultConstructor() // note can't do this in C# yet
    {
        ConstructorInvoked = true;
    }
}

public class ClassWithOptionalArgsCtorWithStructs
{
    public StructWithPublicDefaultConstructor StructWithConstructor { get; }

    public ClassWithOptionalArgsCtorWithStructs(
        StructWithPublicDefaultConstructor structWithConstructor = default
    )
    {
        StructWithConstructor = structWithConstructor;
    }
}

Fails the following test:

Assert.False(class.StructWithConstructor.ConstructorInvoked);

The constructor shouldn't have been invoked because I didn't register StructWithPublicDefaultConstructor as a service. However, debugging into it, the Unit ServiceProvider is finding the ConstructorInfo on the ValueType and invoking it.

Unity is the only DI provider with this behavior. The other providers return null for this Type, and the test passes.

I needed to special case Unity's behavior in this test. So I logged an issue to ensure this is the behavior we are expecting for Unity.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions