Skip to content

Commit 684a03b

Browse files
committed
Defer the exception (if any) when accessing the container
1 parent c746133 commit 684a03b

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/Testcontainers.Xunit/ContainerLifetime.cs

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ public abstract class ContainerLifetime<TBuilderEntity, TContainerEntity> : IAsy
1010
where TContainerEntity : IContainer
1111
{
1212
private readonly Lazy<TContainerEntity> _container;
13+
[CanBeNull] private ExceptionDispatchInfo _exception;
1314

1415
/// <summary>
1516
/// The logger.
@@ -48,17 +49,40 @@ protected ContainerLifetime()
4849
/// <summary>
4950
/// The container instance.
5051
/// </summary>
51-
public TContainerEntity Container => _container.Value;
52+
public TContainerEntity Container
53+
{
54+
get
55+
{
56+
_exception?.Throw();
57+
return _container.Value;
58+
}
59+
}
5260

5361
/// <inheritdoc />
5462
Task IAsyncLifetime.InitializeAsync() => InitializeAsync();
5563

5664
/// <inheritdoc cref="IAsyncLifetime.InitializeAsync()" />
57-
protected virtual Task InitializeAsync() => Container.StartAsync();
65+
protected virtual async Task InitializeAsync()
66+
{
67+
try
68+
{
69+
await Container.StartAsync();
70+
}
71+
catch (Exception e)
72+
{
73+
_exception = ExceptionDispatchInfo.Capture(e);
74+
}
75+
}
5876

5977
/// <inheritdoc />
6078
Task IAsyncLifetime.DisposeAsync() => DisposeAsync();
6179

6280
/// <inheritdoc cref="IAsyncLifetime.DisposeAsync()" />
63-
protected virtual Task DisposeAsync() => Container.DisposeAsync().AsTask();
81+
protected virtual async Task DisposeAsync()
82+
{
83+
if (_exception == null)
84+
{
85+
await Container.DisposeAsync();
86+
}
87+
}
6488
}

src/Testcontainers.Xunit/Usings.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
global using System;
22
global using System.Data.Common;
33
global using System.Diagnostics;
4+
global using System.Runtime.ExceptionServices;
45
global using System.Threading;
56
global using System.Threading.Tasks;
67
global using DotNet.Testcontainers.Builders;

0 commit comments

Comments
 (0)