From 4da6876f3ecd7c34771553d8409b829e287d3041 Mon Sep 17 00:00:00 2001 From: Nikolay Pianikov Date: Fri, 20 Dec 2024 11:47:23 +0300 Subject: [PATCH] Fixed warnings when using nullable types in factories --- src/Pure.DI.Core/Core/Code/BuildTools.cs | 2 +- .../Core/Code/CompositionClassBuilder.cs | 2 +- tests/Pure.DI.IntegrationTests/SetupTests.cs | 55 +++++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) diff --git a/src/Pure.DI.Core/Core/Code/BuildTools.cs b/src/Pure.DI.Core/Core/Code/BuildTools.cs index a8a783a63..543a38d5e 100644 --- a/src/Pure.DI.Core/Core/Code/BuildTools.cs +++ b/src/Pure.DI.Core/Core/Code/BuildTools.cs @@ -57,7 +57,7 @@ private string OnInjectedInternal(BuildContext ctx, Variable variable) if (skipNotNullCheck && (variable.HasCycle || variable.Node.Lifetime is Lifetime.Singleton or Lifetime.Scoped or Lifetime.PerResolve)) { - variableCode = $"{variableCode}!"; + variableCode = $"{variableCode}"; } } diff --git a/src/Pure.DI.Core/Core/Code/CompositionClassBuilder.cs b/src/Pure.DI.Core/Core/Code/CompositionClassBuilder.cs index 6397b5f1c..1d2a0bf38 100644 --- a/src/Pure.DI.Core/Core/Code/CompositionClassBuilder.cs +++ b/src/Pure.DI.Core/Core/Code/CompositionClassBuilder.cs @@ -48,7 +48,7 @@ public CompositionCode Build(CompositionCode composition) code.AppendLine($"// by {information.Description}"); if (composition.Compilation.Options.NullableContextOptions != NullableContextOptions.Disable) { - code.AppendLine("#nullable enable"); + code.AppendLine("#nullable enable annotations"); } code.AppendLine(); diff --git a/tests/Pure.DI.IntegrationTests/SetupTests.cs b/tests/Pure.DI.IntegrationTests/SetupTests.cs index 7b26e0c9c..6c64fadf0 100644 --- a/tests/Pure.DI.IntegrationTests/SetupTests.cs +++ b/tests/Pure.DI.IntegrationTests/SetupTests.cs @@ -1959,4 +1959,59 @@ public static void Main() result.Success.ShouldBeTrue(result); result.StdOut.ShouldBe(["True"], result); } + + [Fact] + public async Task ShouldSupportNullableResultTypeWhenFactory() + { + // Given + + // When + var result = await """ + using System; + using Pure.DI; + using static Pure.DI.DI; + + namespace Sample + { + interface IDependency { }; + + class Dependency : IDependency { } + + interface IService + { + void DoSomething(); + } + + class Service : IService + { + public Service(IDependency? dependency) + { + } + + public void DoSomething() + { + } + } + + public class Program + { + private void Setup() => + DI.Setup(nameof(Composition)) + .Bind().To(_ => default) + .Bind().To() + .Root("Service"); + + public static void Main() + { + var composition = new Composition(); + Console.WriteLine(composition.Service); + } + } + } + """.RunAsync(); + + // Then + result.Success.ShouldBeTrue(result); + result.StdOut.ShouldBe(["Sample.Service"], result); + } } \ No newline at end of file