Skip to content

Commit

Permalink
Support for IContext.Tag with a value of null in factories.
Browse files Browse the repository at this point in the history
  • Loading branch information
NikolayPianikov committed Jan 22, 2024
1 parent a2c3d42 commit 2ab49ef
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Pure.DI.Core/Core/Code/FactoryRewriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
72 changes: 72 additions & 0 deletions tests/Pure.DI.IntegrationTests/FactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(in T value, object? tag, Lifetime lifetime)
{
return value;
}
}
static class Setup
{
private static void SetupComposition()
{
// OnDependencyInjection = On
DI.Setup("Composition")
.Bind<IDependency>(123).To(ctx => new Dependency())
.Bind<IService>().To(ctx => {
System.Console.WriteLine(ctx.Tag ?? "null");
ctx.Inject<IDependency>(123, out var dependency);
return new Service(dependency);
})
.Root<IService>("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()
{
Expand Down

0 comments on commit 2ab49ef

Please sign in to comment.