// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR.Json;
using Microsoft.AspNet.SignalR.Messaging;
using Microsoft.AspNet.SignalR.Tracing;
namespace Microsoft.AspNet.SignalR.Infrastructure
{
///
/// Default implementation.
///
public class ConnectionManager : IConnectionManager
{
private readonly IDependencyResolver _resolver;
private readonly IPerformanceCounterManager _counters;
///
/// Initializes a new instance of the class.
///
/// The .
public ConnectionManager(IDependencyResolver resolver)
{
_resolver = resolver;
_counters = _resolver.Resolve();
}
///
/// Returns a for the .
///
/// Type of the
/// A for the .
public IPersistentConnectionContext GetConnectionContext() where T : PersistentConnection
{
return GetConnection(typeof(T));
}
///
/// Returns a for the .
///
/// Type of the
/// A for the .
public IPersistentConnectionContext GetConnection(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
string rawConnectionName = type.FullName;
string connectionName = PrefixHelper.GetPersistentConnectionName(rawConnectionName);
IConnection connection = GetConnectionCore(connectionName);
return new PersistentConnectionContext(connection, new GroupManager(connection, PrefixHelper.GetPersistentConnectionGroupName(rawConnectionName)));
}
///
/// Returns a for the specified .
///
/// Type of the
/// a for the specified
public IHubContext GetHubContext() where T : IHub
{
return GetHubContext(typeof(T).GetHubName());
}
///
/// Returns a for the specified hub.
///
/// Name of the hub
/// a for the specified hub
public IHubContext GetHubContext(string hubName)
{
var connection = GetConnectionCore(connectionName: null);
var hubManager = _resolver.Resolve();
var pipelineInvoker = _resolver.Resolve();
hubManager.EnsureHub(hubName,
_counters.ErrorsHubResolutionTotal,
_counters.ErrorsHubResolutionPerSec,
_counters.ErrorsAllTotal,
_counters.ErrorsAllPerSec);
Func, Task> send = (signal, value, exclude) => pipelineInvoker.Send(new HubOutgoingInvokerContext(connection, signal, value, exclude));
return new HubContext(send, hubName, connection);
}
internal Connection GetConnectionCore(string connectionName)
{
IList signals = connectionName == null ? ListHelper.Empty : new[] { connectionName };
// Give this a unique id
var connectionId = Guid.NewGuid().ToString();
return new Connection(_resolver.Resolve(),
_resolver.Resolve(),
connectionName,
connectionId,
signals,
ListHelper.Empty,
_resolver.Resolve(),
_resolver.Resolve(),
_resolver.Resolve(),
_resolver.Resolve());
}
}
}