Skip to content

Inconsistent behavior of different RegistrationExtensions.WithProperty overloads regarding nullable properties #1427

@maxmitti

Description

@maxmitti

Describe the Bug

The WithProperty(Expression<Func<TLimit, TProperty>> propertyExpression, TProperty propertyValue) throws when propertyValue is null, regardless whether TProperty is nullable. Nullable analysis does not flag an issue when passing null.
The relevant check is here:

if (propertyValue == null)
{
throw new ArgumentNullException(nameof(propertyValue));
}

All other WithProperty overloads accept null or null!.

Steps to Reproduce

using Autofac;
using System;
using Xunit;

namespace Tests;

public class WithPropertyTests
{
    private class Test
    {
        public required int? Property { get; init; }
    }

    [Fact]
    public void WithProperty_NullPropertyValue()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<Test>()
            .WithProperty(nameof(Test.Property), null!)
            .AsSelf();

        builder.RegisterType<Test>()
            .WithProperty(new TypedParameter(typeof(int?), null))
            .AsSelf();

        Exception? exception = Record.Exception(() =>
            builder.RegisterType<Test>()
                .WithProperty(t => t.Property, null)
                .AsSelf());
        Assert.Null(exception);
    }
}

Expected Behavior

I would expect WithProperty(Expression<Func<TLimit, TProperty>> propertyExpression, TProperty propertyValue) to accept a null propertyValue when TProperty is nullable, similar to the other overloads.

Exception with Stack Trace

Xunit.Sdk.NullException
Assert.Null() Failure: Value is not null
Expected: null
Actual:   System.ArgumentNullException: Value cannot be null. (Parameter 'propertyValue')
   at Autofac.RegistrationExtensions.WithProperty[TLimit,TReflectionActivatorData,TStyle,TProperty](IRegistrationBuilder`3 registration, Expression`1 propertyExpression, TProperty propertyValue)
   at Tests.WithPropertyTests.<>c__DisplayClass1_0.<WithProperty_NullPropertyValue>b__0() in […]\Tests\WithPropertyTests.cs:line 27
   at Xunit.Record.Exception(Func`1 testCode) in /_/src/xunit.core/Record.cs:line 47
   at Tests.WithPropertyTests.WithProperty_NullPropertyValue() in […]\Tests\WithPropertyTests.cs:line 30
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)

Dependency Versions

Autofac: 7.1.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions