diff --git a/Pure.DI.Tests/Integration/SingletonTests.cs b/Pure.DI.Tests/Integration/SingletonTests.cs index dc742f88..c4d45674 100644 --- a/Pure.DI.Tests/Integration/SingletonTests.cs +++ b/Pure.DI.Tests/Integration/SingletonTests.cs @@ -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().As(Lifetime.Singleton).To() + .Bind().To(); + } + } + }".Run(out var generatedCode); + + // Then + output.ShouldBe(new[] + { + "Sample.Foo" + }, generatedCode); + } } \ No newline at end of file diff --git a/Pure.DI/Core/DisposeStatementsBuilder.cs b/Pure.DI/Core/DisposeStatementsBuilder.cs index a02ee41d..b04c3975 100644 --- a/Pure.DI/Core/DisposeStatementsBuilder.cs +++ b/Pure.DI/Core/DisposeStatementsBuilder.cs @@ -17,8 +17,13 @@ public IEnumerable 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()) ) ); } diff --git a/Pure.DI/Core/SyntaxRepo.cs b/Pure.DI/Core/SyntaxRepo.cs index b366cb49..9e04cd23 100644 --- a/Pure.DI/Core/SyntaxRepo.cs +++ b/Pure.DI/Core/SyntaxRepo.cs @@ -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());