Skip to content

Commit

Permalink
Fixed warnings when using nullable types in factories
Browse files Browse the repository at this point in the history
  • Loading branch information
NikolayPianikov committed Dec 20, 2024
1 parent 7a804ff commit 4da6876
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/Pure.DI.Core/Core/Code/BuildTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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}";
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Pure.DI.Core/Core/Code/CompositionClassBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
55 changes: 55 additions & 0 deletions tests/Pure.DI.IntegrationTests/SetupTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<IDependency?>().To<IDependency?>(_ => default)
.Bind<IService>().To<Service>()
.Root<IService>("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);
}
}

0 comments on commit 4da6876

Please sign in to comment.