Adding HubConnectionBuilder

This commit is contained in:
Pawel Kadluczka 2017-09-01 11:36:16 -07:00
parent 9e614b6cc7
commit 4ac8e786cf
15 changed files with 315 additions and 27 deletions

View File

@ -30,11 +30,13 @@ namespace ClientSample
{
baseUrl = string.IsNullOrEmpty(baseUrl) ? "http://localhost:5000/default" : baseUrl;
var loggerFactory = new LoggerFactory();
Console.WriteLine("Connecting to {0}", baseUrl);
var httpConnection = new HttpConnection(new Uri(baseUrl));
var connection = new HubConnection(httpConnection, loggerFactory);
var connection = new HubConnectionBuilder()
.WithUrl(baseUrl)
.WithConsoleLogger()
.Build();
try
{
await connection.StartAsync();

View File

@ -0,0 +1,9 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Sockets.Client;
namespace Microsoft.AspNetCore.SignalR.Client
{
public delegate IConnection ConnectionFactoryDelegate();
}

View File

@ -51,15 +51,6 @@ namespace Microsoft.AspNetCore.SignalR.Client
remove { _connection.Closed -= value; }
}
public HubConnection(IConnection connection)
: this(connection, new JsonHubProtocol(new JsonSerializer()), null)
{ }
// These are only really needed for tests now...
public HubConnection(IConnection connection, ILoggerFactory loggerFactory)
: this(connection, new JsonHubProtocol(new JsonSerializer()), loggerFactory)
{ }
public HubConnection(IConnection connection, IHubProtocol protocol, ILoggerFactory loggerFactory)
{
if (connection == null)

View File

@ -0,0 +1,75 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.AspNetCore.SignalR.Internal.Protocol;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.SignalR.Client
{
public class HubConnectionBuilder : IHubConnectionBuilder
{
private readonly Dictionary<KeyValuePair<string, Type>, object> _settings = new Dictionary<KeyValuePair<string, Type>, object>();
private ConnectionFactoryDelegate _connectionFactoryDelegate;
public void ConfigureConnectionFactory(ConnectionFactoryDelegate connectionFactoryDelegate) =>
_connectionFactoryDelegate = connectionFactoryDelegate;
public void AddSetting<T>(string name, T value)
{
_settings[new KeyValuePair<string, Type>(name, typeof(T))] = value;
}
public bool TryGetSetting<T>(string name, out T value)
{
value = default(T);
if (!_settings.TryGetValue(new KeyValuePair<string, Type>(name, typeof(T)), out var setting))
{
return false;
}
value = (T)setting;
return true;
}
public HubConnection Build()
{
if (_connectionFactoryDelegate == null)
{
throw new InvalidOperationException("Cannot create IConnection instance. The connection factory was not configured.");
}
var connection = _connectionFactoryDelegate();
var loggerFactory = ((IHubConnectionBuilder)this).GetLoggerFactory();
var hubProtocol = ((IHubConnectionBuilder)this).GetHubProtocol();
return new HubConnection(connection, hubProtocol ?? new JsonHubProtocol(new JsonSerializer()), loggerFactory);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return base.GetHashCode();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
return base.Equals(obj);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString()
{
return base.ToString();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public new Type GetType()
{
return base.GetType();
}
}
}

View File

@ -0,0 +1,11 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNetCore.SignalR.Client
{
public static class HubConnectionBuilderDefaults
{
public static readonly string LoggerFactoryKey = "LoggerFactory";
public static readonly string HubProtocolKey = "HubProtocol";
}
}

View File

@ -0,0 +1,46 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.SignalR.Internal.Protocol;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.SignalR.Client
{
public static class HubConnectionBuilderExtensions
{
public static IHubConnectionBuilder WithHubProtocol(this IHubConnectionBuilder hubConnectionBuilder, IHubProtocol hubProtocol)
{
hubConnectionBuilder.AddSetting(HubConnectionBuilderDefaults.HubProtocolKey, hubProtocol);
return hubConnectionBuilder;
}
public static IHubConnectionBuilder WithJsonProtocol(this IHubConnectionBuilder hubConnectionBuilder)
{
return hubConnectionBuilder.WithHubProtocol(new JsonHubProtocol(new JsonSerializer()));
}
public static IHubConnectionBuilder WithMessagePackProtocol(this IHubConnectionBuilder hubConnectionBuilder)
{
return hubConnectionBuilder.WithHubProtocol(new MessagePackHubProtocol());
}
public static IHubConnectionBuilder WithLogger(this IHubConnectionBuilder hubConnectionBuilder, ILoggerFactory loggerFactory)
{
hubConnectionBuilder.AddSetting(HubConnectionBuilderDefaults.LoggerFactoryKey, loggerFactory);
return hubConnectionBuilder;
}
public static ILoggerFactory GetLoggerFactory(this IHubConnectionBuilder hubConnectionBuilder)
{
hubConnectionBuilder.TryGetSetting<ILoggerFactory>(HubConnectionBuilderDefaults.LoggerFactoryKey, out var loggerFactory);
return loggerFactory;
}
public static IHubProtocol GetHubProtocol(this IHubConnectionBuilder hubConnectionBuilder)
{
hubConnectionBuilder.TryGetSetting<IHubProtocol>(HubConnectionBuilderDefaults.LoggerFactoryKey, out var hubProtocol);
return hubProtocol;
}
}
}

View File

@ -0,0 +1,13 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNetCore.SignalR.Client
{
public interface IHubConnectionBuilder
{
void AddSetting<T>(string name, T value);
bool TryGetSetting<T>(string name, out T value);
void ConfigureConnectionFactory(ConnectionFactoryDelegate connectionFactory);
HubConnection Build();
}
}

View File

@ -0,0 +1,26 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.SignalR.Client
{
public static class HubConnectionBuilderExtensions
{
public static IHubConnectionBuilder WithConsoleLogger(this IHubConnectionBuilder hubConnectionBuilder)
{
return hubConnectionBuilder.WithConsoleLogger(new LoggerFactory());
}
public static IHubConnectionBuilder WithConsoleLogger(this IHubConnectionBuilder hubConnectionBuilder, ILoggerFactory loggerFactory)
{
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
return hubConnectionBuilder.WithLogger(loggerFactory.AddConsole());
}
}
}

View File

@ -0,0 +1,71 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net.Http;
using Microsoft.AspNetCore.Sockets;
using Microsoft.AspNetCore.Sockets.Client;
namespace Microsoft.AspNetCore.SignalR.Client
{
public static class HubConnectionBuilderHttpExtensions
{
public static readonly string TransportTypeKey = "TransportType";
public static readonly string HttpMessageHandlerKey = "HttpMessageHandler";
public static IHubConnectionBuilder WithUrl(this IHubConnectionBuilder hubConnectionBuilder, string url)
{
if (url == null)
{
throw new ArgumentNullException(nameof(url));
}
return hubConnectionBuilder.WithUrl(new Uri(url));
}
public static IHubConnectionBuilder WithUrl(this IHubConnectionBuilder hubConnectionBuilder, Uri url)
{
if (url == null)
{
throw new ArgumentNullException(nameof(url));
}
hubConnectionBuilder.ConfigureConnectionFactory(() =>
{
return new HttpConnection(url,
hubConnectionBuilder.GetTransportType(),
hubConnectionBuilder.GetLoggerFactory(),
hubConnectionBuilder.GetMessageHandler());
});
return hubConnectionBuilder;
}
public static IHubConnectionBuilder WithTransportType(this IHubConnectionBuilder hubConnectionBuilder, TransportType transportType)
{
hubConnectionBuilder.AddSetting(TransportTypeKey, transportType);
return hubConnectionBuilder;
}
public static IHubConnectionBuilder WithMessageHandler(this IHubConnectionBuilder hubConnectionBuilder, HttpMessageHandler httpMessageHandler)
{
hubConnectionBuilder.AddSetting(HttpMessageHandlerKey, httpMessageHandler);
return hubConnectionBuilder;
}
public static TransportType GetTransportType(this IHubConnectionBuilder hubConnectionBuilder)
{
if (hubConnectionBuilder.TryGetSetting<TransportType>(TransportTypeKey, out var transportType))
{
return transportType;
}
return TransportType.All;
}
public static HttpMessageHandler GetMessageHandler(this IHubConnectionBuilder hubConnectionBuilder)
{
hubConnectionBuilder.TryGetSetting<HttpMessageHandler>(HttpMessageHandlerKey, out var messageHandler);
return messageHandler;
}
}
}

View File

@ -10,4 +10,9 @@
<ProjectReference Include="..\Microsoft.AspNetCore.Sockets.Client.Http\Microsoft.AspNetCore.Sockets.Client.Http.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="$(AspNetCoreVersion)" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="$(AspNetCoreVersion)" />
</ItemGroup>
</Project>

View File

@ -1,11 +1,6 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.SignalR
{
public interface IHubContext<THub> where THub : Hub

View File

@ -44,8 +44,13 @@ namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests
{
using (StartLog(out var loggerFactory))
{
var httpConnection = new HttpConnection(new Uri(_serverFixture.BaseUrl + path), transportType, loggerFactory);
var connection = new HubConnection(httpConnection, protocol, loggerFactory);
var connection = new HubConnectionBuilder()
.WithUrl(_serverFixture.BaseUrl + path)
.WithTransportType(transportType)
.WithLogger(loggerFactory)
.WithHubProtocol(protocol)
.Build();
try
{
await connection.StartAsync().OrTimeout();

View File

@ -0,0 +1,34 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Xunit;
namespace Microsoft.AspNetCore.SignalR.Client.Tests
{
public class HubConnectionBuilderTests
{
[Fact]
public void HubConnectionBuiderThrowsIfConnectionFactoryNotConfigured()
{
var ex = Assert.Throws<InvalidOperationException>(() => new HubConnectionBuilder().Build());
Assert.Equal("Cannot create IConnection instance. The connection factory was not configured.", ex.Message);
}
[Fact]
public void WithUrlThrowsForNullUrls()
{
Assert.Equal("url",
Assert.Throws<ArgumentNullException>(() => new HubConnectionBuilder().WithUrl((string)null)).ParamName);
Assert.Equal("url",
Assert.Throws<ArgumentNullException>(() => new HubConnectionBuilder().WithUrl((Uri)null)).ParamName);
}
[Fact]
public void WithConsoleLoggerThrowsForNullLoggerFactory()
{
Assert.Equal("loggerFactory",
Assert.Throws<ArgumentNullException>(() => new HubConnectionBuilder().WithConsoleLogger(null)).ParamName);
}
}
}

View File

@ -12,6 +12,7 @@ using Microsoft.AspNetCore.SignalR.Tests.Common;
using Microsoft.AspNetCore.Sockets.Client;
using Microsoft.Extensions.Logging;
using Moq;
using Newtonsoft.Json;
using Xunit;
namespace Microsoft.AspNetCore.SignalR.Client.Tests
@ -24,7 +25,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests
var connection = new Mock<IConnection>();
connection.SetupGet(p => p.Features).Returns(new FeatureCollection());
connection.Setup(m => m.StartAsync()).Returns(Task.CompletedTask).Verifiable();
var hubConnection = new HubConnection(connection.Object);
var hubConnection = new HubConnection(connection.Object, Mock.Of<IHubProtocol>(), null);
await hubConnection.StartAsync();
connection.Verify(c => c.StartAsync(), Times.Once());
@ -35,7 +36,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests
{
var connection = new Mock<IConnection>();
connection.Setup(m => m.StartAsync()).Verifiable();
var hubConnection = new HubConnection(connection.Object);
var hubConnection = new HubConnection(connection.Object, Mock.Of<IHubProtocol>(), null);
await hubConnection.DisposeAsync();
connection.Verify(c => c.DisposeAsync(), Times.Once());
@ -58,7 +59,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests
public async Task HubConnectionConnectedEventRaisedWhenTheClientIsConnected()
{
var connection = new TestConnection();
var hubConnection = new HubConnection(connection);
var hubConnection = new HubConnection(connection, Mock.Of<IHubProtocol>(), null);
try
{
var connectedEventRaisedTcs = new TaskCompletionSource<object>();
@ -81,7 +82,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests
[Fact]
public async Task ClosedEventRaisedWhenTheClientIsStopped()
{
var hubConnection = new HubConnection(new TestConnection());
var hubConnection = new HubConnection(new TestConnection(), Mock.Of<IHubProtocol>(), null);
var closedEventTcs = new TaskCompletionSource<Exception>();
hubConnection.Closed += e =>
{
@ -99,7 +100,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests
public async Task CannotCallInvokeOnClosedHubConnection()
{
var connection = new TestConnection();
var hubConnection = new HubConnection(connection, new LoggerFactory());
var hubConnection = new HubConnection(connection, new JsonHubProtocol(new JsonSerializer()), new LoggerFactory());
await hubConnection.StartAsync();
await hubConnection.DisposeAsync();
@ -113,7 +114,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests
public async Task PendingInvocationsAreCancelledWhenConnectionClosesCleanly()
{
var connection = new TestConnection();
var hubConnection = new HubConnection(connection, new LoggerFactory());
var hubConnection = new HubConnection(connection, new JsonHubProtocol(new JsonSerializer()), new LoggerFactory());
await hubConnection.StartAsync();
var invokeTask = hubConnection.InvokeAsync<int>("testMethod");
@ -133,7 +134,7 @@ namespace Microsoft.AspNetCore.SignalR.Client.Tests
.Callback(() => mockConnection.Raise(c => c.Closed += null, exception))
.Returns(Task.FromResult<object>(null));
var hubConnection = new HubConnection(mockConnection.Object, new LoggerFactory());
var hubConnection = new HubConnection(mockConnection.Object, Mock.Of<IHubProtocol>(), new LoggerFactory());
await hubConnection.StartAsync();
var invokeTask = hubConnection.InvokeAsync<int>("testMethod");

View File

@ -284,7 +284,11 @@ namespace Microsoft.AspNetCore.SignalR.Tests
var url = _serverFixture.BaseUrl + "/uncreatable";
var connection = new HubConnection(new HttpConnection(new Uri(url), transportType, loggerFactory), loggerFactory);
var connection = new HubConnectionBuilder()
.WithUrl(new Uri(url))
.WithTransportType(transportType)
.WithLogger(loggerFactory)
.Build();
try
{
var closeTcs = new TaskCompletionSource<object>();