Skip to content

Commit 08b16aa

Browse files
authored
Better Dispose pattern for WebSocketConnection (#673)
1 parent d4090a7 commit 08b16aa

File tree

3 files changed

+14
-13
lines changed

3 files changed

+14
-13
lines changed

src/Transports.Subscriptions.WebSockets/GraphQLWebSocketsMiddleware.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,9 @@ await socket.CloseAsync(
6161
using (_logger.BeginScope($"GraphQL websocket connection: {context.Connection.Id}"))
6262
{
6363
var connectionFactory = context.RequestServices.GetRequiredService<IWebSocketConnectionFactory<TSchema>>();
64-
var connection = connectionFactory.CreateConnection(socket, context.Connection.Id);
64+
using var connection = connectionFactory.CreateConnection(socket, context.Connection.Id);
6565

66+
// Wait until the websocket has disconnected (and all subscriptions ended)
6667
await connection.Connect();
6768
}
6869
}
Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1+
using System;
12
using System.Threading.Tasks;
23
using GraphQL.Server.Transports.Subscriptions.Abstractions;
34

45
namespace GraphQL.Server.Transports.WebSockets
56
{
6-
public class WebSocketConnection
7+
public class WebSocketConnection : IDisposable
78
{
89
private readonly WebSocketTransport _transport;
910
private readonly SubscriptionServer _server;
@@ -18,16 +19,14 @@ public WebSocketConnection(
1819

1920
public virtual async Task Connect()
2021
{
21-
try
22-
{
23-
await _server.OnConnect();
24-
await _server.OnDisconnect();
25-
await _transport.CloseAsync();
26-
}
27-
finally
28-
{
29-
_transport.Dispose();
30-
}
22+
await _server.OnConnect();
23+
await _server.OnDisconnect();
24+
await _transport.CloseAsync();
25+
}
26+
27+
public void Dispose()
28+
{
29+
_transport.Dispose();
3130
}
3231
}
3332
}

tests/ApiApprovalTests/GraphQL.Server.Transports.Subscriptions.WebSockets.approved.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,11 @@ namespace GraphQL.Server.Transports.WebSockets
1818
{
1919
GraphQL.Server.Transports.WebSockets.WebSocketConnection CreateConnection(System.Net.WebSockets.WebSocket socket, string connectionId);
2020
}
21-
public class WebSocketConnection
21+
public class WebSocketConnection : System.IDisposable
2222
{
2323
public WebSocketConnection(GraphQL.Server.Transports.WebSockets.WebSocketTransport transport, GraphQL.Server.Transports.Subscriptions.Abstractions.SubscriptionServer subscriptionServer) { }
2424
public virtual System.Threading.Tasks.Task Connect() { }
25+
public void Dispose() { }
2526
}
2627
public class WebSocketConnectionFactory<TSchema> : GraphQL.Server.Transports.WebSockets.IWebSocketConnectionFactory<TSchema>
2728
where TSchema : GraphQL.Types.ISchema

0 commit comments

Comments
 (0)