Skip to content

Commit

Permalink
Support explicit sisposable when singleton lifetime
Browse files Browse the repository at this point in the history
  • Loading branch information
NikolayPianikov authored and NikolayPianikov committed Jun 24, 2022
1 parent 0772112 commit 0378d54
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 3 deletions.
41 changes: 41 additions & 0 deletions Pure.DI.Tests/Integration/SingletonTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -240,4 +240,45 @@ static Composer()
"True"
}, generatedCode);
}

[Fact]
public void ShouldSupportExplicitDisposableWhenSingleton()
{
// Given

// When
var output = @"
namespace Sample
{
using System;
using Pure.DI;
public class CompositionRoot
{
public readonly Foo Value;
internal CompositionRoot(Foo value) => Value = value;
}
public class Foo: IDisposable
{
void IDisposable.Dispose() {}
}
internal static partial class Composer
{
static Composer()
{
DI.Setup()
.Bind<Foo>().As(Lifetime.Singleton).To<Foo>()
.Bind<CompositionRoot>().To<CompositionRoot>();
}
}
}".Run(out var generatedCode);

// Then
output.ShouldBe(new[]
{
"Sample.Foo"
}, generatedCode);
}
}
9 changes: 7 additions & 2 deletions Pure.DI/Core/DisposeStatementsBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,13 @@ public IEnumerable<StatementSyntax> Build(MemberAccessExpressionSyntax instanceE
SyntaxFactory.InvocationExpression(
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
instanceExpression,
SyntaxFactory.IdentifierName(nameof(IDisposable.Dispose)))).AddArgumentListArguments())
SyntaxFactory.ParenthesizedExpression(
SyntaxFactory.CastExpression(
SyntaxRepo.DisposableTypeSyntax,
instanceExpression)
),
SyntaxFactory.IdentifierName(nameof(IDisposable.Dispose)))
).AddArgumentListArguments())
)
);
}
Expand Down
2 changes: 1 addition & 1 deletion Pure.DI/Core/SyntaxRepo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ internal static class SyntaxRepo
public const string RaiseOnDisposableMethodName = "RaiseOnDisposable";
private static readonly TypeSyntax VoidTypeSyntax = SyntaxFactory.ParseTypeName("void");
public static readonly TypeSyntax BoolTypeSyntax = SyntaxFactory.ParseTypeName("bool");
private static readonly TypeSyntax DisposableTypeSyntax = SyntaxFactory.ParseTypeName(typeof(IDisposable).ToString());
public static readonly TypeSyntax DisposableTypeSyntax = SyntaxFactory.ParseTypeName(typeof(IDisposable).ToString());
public static readonly TypeSyntax TTypeSyntax = SyntaxFactory.ParseTypeName("T");
public static readonly TypeSyntax TypeTypeSyntax = SyntaxFactory.ParseTypeName(typeof(Type).ToString());
public static readonly TypeSyntax UIntTypeSyntax = SyntaxFactory.ParseTypeName(typeof(uint).ToString());
Expand Down

0 comments on commit 0378d54

Please sign in to comment.