From 2ab49ef8185579b3b7570e687b68bac816de0008 Mon Sep 17 00:00:00 2001 From: Nikolay Pianikov Date: Mon, 22 Jan 2024 18:35:31 +0300 Subject: [PATCH] Support for `IContext.Tag` with a value of `null` in factories. --- src/Pure.DI.Core/Core/Code/FactoryRewriter.cs | 5 ++ .../Pure.DI.IntegrationTests/FactoryTests.cs | 72 +++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/src/Pure.DI.Core/Core/Code/FactoryRewriter.cs b/src/Pure.DI.Core/Core/Code/FactoryRewriter.cs index 00348d5f3..45cc8c274 100644 --- a/src/Pure.DI.Core/Core/Code/FactoryRewriter.cs +++ b/src/Pure.DI.Core/Core/Code/FactoryRewriter.cs @@ -218,6 +218,11 @@ public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax no { return SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, token); } + + if (token.IsKind(SyntaxKind.NullKeyword)) + { + return SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, token); + } } return base.VisitMemberAccessExpression(node); diff --git a/tests/Pure.DI.IntegrationTests/FactoryTests.cs b/tests/Pure.DI.IntegrationTests/FactoryTests.cs index 4892ec26f..1df5b5dcb 100644 --- a/tests/Pure.DI.IntegrationTests/FactoryTests.cs +++ b/tests/Pure.DI.IntegrationTests/FactoryTests.cs @@ -792,6 +792,78 @@ public static void Main() result.StdOut.ShouldBe(ImmutableArray.Create("123", "Created"), result); } + [Fact] + public async Task ShouldReplaceContextTagWhenTagIsNull() + { + // Given + + // When + var result = await """ +using System; +using Pure.DI; + +namespace Sample +{ + interface IDependency {} + + class Dependency: IDependency {} + + interface IService + { + IDependency Dep { get; } + } + + class Service: IService + { + public Service(IDependency dep) + { + Dep = dep; + Console.WriteLine("Created"); + } + + public IDependency Dep { get; } + } + + internal partial class Composition + { + private partial T OnDependencyInjection(in T value, object? tag, Lifetime lifetime) + { + return value; + } + } + + static class Setup + { + private static void SetupComposition() + { + // OnDependencyInjection = On + DI.Setup("Composition") + .Bind(123).To(ctx => new Dependency()) + .Bind().To(ctx => { + System.Console.WriteLine(ctx.Tag ?? "null"); + ctx.Inject(123, out var dependency); + return new Service(dependency); + }) + .Root("Service"); + } + } + + public class Program + { + public static void Main() + { + var composition = new Composition(); + var service = composition.Service; + } + } +} +""".RunAsync(new Options(LanguageVersion.CSharp9)); + + // Then + result.Success.ShouldBeTrue(result); + result.StdOut.ShouldBe(ImmutableArray.Create("null", "Created"), result); + } + [Fact] public async Task ShouldSupportFactoryWithInjectWhenGenericTypeIsNotSpecifiedAsTypeArgument() {