コード例 #1
0
ファイル: NetServer.cs プロジェクト: 15831944/Test3-1
 void GetPropertyValues(ServiceProtocol serviceProtocol, Int64 requestID, ref ArrayList propertyList)
 {
     // Return modified ArrayList with tag details included.
 }
コード例 #2
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
  bool ModifyThingPath(ServiceProtocol serviceProtocol, Int64 requestID, Guid guid, String path)
  {
    if (true) // Decide whether to modify an item.
    { // We're going to do it.
      // Modify the item.

      // Raise event(s).
      serviceProtocol.DoThingPathModified(requestID, guid, path);

      return true;
    }
    else
    { // We're not going to do it.
      return false;
    }
  }
コード例 #3
0
        /// <summary> 获取服务 </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="provider"></param>
        /// <param name="protocol"></param>
        /// <returns></returns>
        public static T GetService <T>(this IServiceProvider provider, ServiceProtocol protocol)
        {
            var list = provider.GetServices <T>();

            return(list.First(t => t.GetType().GetCustomAttribute <ProtocolAttribute>()?.Protocol == protocol));
        }
コード例 #4
0
ファイル: ProtocolAttribute.cs プロジェクト: ohngahng/spear
 public ProtocolAttribute(ServiceProtocol protocol)
 {
     Protocol = protocol;
 }
コード例 #5
0
 public async Task RegisterRpcRoutes(double processorTime, ServiceProtocol serviceProtocol)
 {
     await _serviceRouteManager.RegisterRpcRoutes(processorTime, serviceProtocol);
 }
コード例 #6
0
        public async Task ClientConnectionContextAbortCanSendOutCloseMessage()
        {
            using (StartVerifiableLog(out var loggerFactory, LogLevel.Trace, expectedErrors: c => true,
                                      logChecker: logs =>
            {
                return(true);
            }))
            {
                var            ccm                 = new TestClientConnectionManager();
                var            ccf                 = new ClientConnectionFactory();
                var            protocol            = new ServiceProtocol();
                TestConnection transportConnection = null;
                var            connectionFactory   = new TestConnectionFactory(conn =>
                {
                    transportConnection = conn;
                    return(Task.CompletedTask);
                });

                var services          = new ServiceCollection();
                var lastWill          = "This is the last will";
                var connectionHandler = new LastWillConnectionHandler(lastWill);
                services.AddSingleton(connectionHandler);
                var builder = new ConnectionBuilder(services.BuildServiceProvider());
                builder.UseConnectionHandler <LastWillConnectionHandler>();
                ConnectionDelegate handler = builder.Build();

                var connection = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf,
                                                       "serverId", Guid.NewGuid().ToString("N"), null, null, closeTimeOutMilliseconds: 500);

                var connectionTask = connection.StartAsync();

                // completed handshake
                await connection.ConnectionInitializedTask.OrTimeout();

                Assert.Equal(ServiceConnectionStatus.Connected, connection.Status);
                var clientConnectionId = Guid.NewGuid().ToString();

                await transportConnection.Application.Output.WriteAsync(
                    protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { })));

                var clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout();

                await clientConnection.LifetimeTask.OrTimeout();

                transportConnection.Transport.Output.Complete();
                var input = await transportConnection.Application.Input.ReadAsync();

                var buffer   = input.Buffer;
                var canParse = protocol.TryParseMessage(ref buffer, out var msg);
                Assert.True(canParse);
                var message = msg as ConnectionDataMessage;
                Assert.NotNull(message);

                Assert.Equal(clientConnectionId, message.ConnectionId);
                Assert.Equal(lastWill, Encoding.UTF8.GetString(message.Payload.First.ToArray()));

                // complete reading to end the connection
                transportConnection.Application.Output.Complete();

                // 1s for application task to timeout
                await connectionTask.OrTimeout(1000);

                Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status);
                Assert.Empty(ccm.ClientConnections);
            }
        }
コード例 #7
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
 void Sync(ServiceProtocol serviceProtocol, Int64 requestID)
 {
   serviceProtocol.Sync(requestID);
 }
コード例 #8
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
  ArrayList PropertyListCheck(ServiceProtocol serviceProtocol, Guid guid, String tag, String path)
  {
    //char* dest = new char[tag.Length+1];
    //strcpy(dest, static_cast<LPCTSTR>(const_cast<void*>(static_cast<const void*>(System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(tag)))));
    //ScdMainWnd().PostMessage(WMU_TAGACTION, SUB_TAGACTION_FINDANDACCESS, (LPARAM)dest);

    ArrayList list = new ArrayList();
    // Generate list of properties at this level in properties tree.
    return list;
  }
コード例 #9
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
   void GetPropertyValues(ServiceProtocol serviceProtocol, Int64 requestID, ref ArrayList propertyList)
 {
   // Return modified ArrayList with tag details included.
 }
コード例 #10
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
  void GetSubTags(ServiceProtocol serviceProtocol, Int64 requestID, String propertyPath, out ArrayList propertyList)
  {
    propertyList = new ArrayList();
    Random random = new Random();

    // Return ArrayList with tag details included.
    for (int i=0; i<10; i++)
    {
      StringBuilder builder = new StringBuilder();
      System.Char ch;
      int n = random.Next(5, 10);
      for (int j = 0; j < n; j++)
      {
        ch = Convert.ToChar(random.Next(33, 126));
        builder.Append(ch);
      }
      switch (random.Next(0, 3))
      {
      case 0:
        propertyList.Add(new ModelProperty(builder.ToString(), random.Next()));
        break;
      case 1:
        propertyList.Add(new ModelProperty(builder.ToString(), random.NextDouble()));
        break;
      case 2:
        propertyList.Add(new ModelProperty(builder.ToString(), builder.ToString()));
        break;
      case 3:
        propertyList.Add(new ModelProperty(builder.ToString(), Color.FromArgb(random.Next())));
        break;
      }
    }
  }
コード例 #11
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
  bool ChangeState(ServiceProtocol serviceProtocol, Int64 requestID, BaseProtocol.RunStates runState)
  {
    if (true) // Decide whether to allow runstate change
    { // We're going to do it.
      // Change the runstate.

      // Raise event(s).
      serviceProtocol.DoStateChanged(requestID, runState);

      return true;
    }
    else
    { // We're not going to do it.
      return false;
    }
  }
コード例 #12
0
 public ServiceDomain(string domain, ServiceProtocol protocol)
 {
     _domain = domain;
     _protocol = protocol;
 }
コード例 #13
0
ファイル: NetServer.cs プロジェクト: 15831944/Test3-1
 void Sync(ServiceProtocol serviceProtocol, Int64 requestID)
 {
     serviceProtocol.Sync(requestID);
 }
コード例 #14
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
  bool DeleteThing(ServiceProtocol serviceProtocol, Int64 requestID, Guid guid)
  {
    if (true) // Decide whether to delete an Thing.
    { // We're going to do it.
      // Delete the Thing.

      // Raise event(s).
      serviceProtocol.DoThingDeleted(requestID, guid);

      return true;
    }
    else
    { // We're not going to do it.
      return false;
    }
  }
コード例 #15
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
  bool CreateItem(ServiceProtocol serviceProtocol, Int64 requestID, Guid guid, String tag, String path, Model model, Shape stencil, RectangleF boundingRect, Single angle, System.Drawing.Color fillColor, System.Drawing.Drawing2D.FillMode fillMode, bool mirrorX, bool mirrorY)
  {
    // Need to check for runstate here, and decide if we'll fire DoItemCreated.
    // This is required in case a rogue client tries to create an item even when not supposed to.
    // This applies to all three create*, and all three delete* events.
    if (true) // Decide whether to create an item.
    { // We're going to do it.
      // Create the item.

      // Raise event(s).
      serviceProtocol.DoItemCreated(requestID, guid, tag, path, model, stencil, boundingRect, angle, fillColor, fillMode, mirrorX, mirrorY);

      return true;
    }
    else
    { // We're not going to do it.
      return false;
    }
  }
コード例 #16
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
 PortStatus PortCheck(ServiceProtocol serviceProtocol, Guid guid, Anchor anchor)
 {
   //		CNSGuidItem * pGuid = new CNSGuidItem();
   //		pGuid.m_Guid = guid;
   //		m_pUnmanaged.m_Guids.AddTail(null);
   //		CNSGuidItem * pGuid = m_pUnmanaged.m_Guids.Find(guid);
   //		CNSMdlLink * pLink = dynamic_cast<CNSMdlLink *>(guid);
   return PortStatus.Available;
 }
コード例 #17
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
  bool ModifyItem(ServiceProtocol serviceProtocol, Int64 requestID, Guid guid, String tag, String path, Model model, Shape stencil, RectangleF boundingRect, Single angle, System.Drawing.Color fillColor, System.Drawing.Drawing2D.FillMode fillMode, bool mirrorX, bool mirrorY)
  {
    if (true) // Decide whether to modify an item.
    { // We're going to do it.

      // Modify the item.

      // Need to get hold of a valid pDoc pointer... *********

      //Individual changes would go something like this: *********
      //int length = tag.Length;
      //wchar_t * tagwc = (wchar_t*)(void*)Marshal.StringToHGlobalUni(tag);

      //char * tagc = (char *)malloc(length+1);
      //tagc[length] = 0;
      //for (int i=0; i<length; i++)
      //  tagc[i] = (char)tagwc[i];

      //pDoc.GCB.DoModify(tagc, 
      //                    angle,
      //                    boundingRect, 
      //                    fillColor,
      //                    fillMode,
      //                    mirrorX,
      //                    mirrorY);

      // Raise event(s).
      serviceProtocol.DoItemModified(requestID, guid, tag, path, model, stencil, boundingRect, angle, fillColor, fillMode, mirrorX, mirrorY);

      return true;
    }
    else
    { // We're not going to do it.
      return false;
    }
  }
コード例 #18
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
  public void MarshalServiceInterface(String filename)
  {
    ServiceProtocol.ChangeStateHandler changeState = new ServiceProtocol.ChangeStateHandler(ChangeState);

    ServiceProtocol.GetPropertyValuesHandler getPropertyValues = new ServiceProtocol.GetPropertyValuesHandler(GetPropertyValues);
    ServiceProtocol.GetSubTagsHandler getSubTags = new ServiceProtocol.GetSubTagsHandler(GetSubTags);

    ServiceProtocol.CreateItemHandler createItem = new ServiceProtocol.CreateItemHandler(CreateItem);
    ServiceProtocol.ModifyItemHandler modifyItem = new ServiceProtocol.ModifyItemHandler(ModifyItem);
    ServiceProtocol.ModifyItemPathHandler modifyItemPath = new ServiceProtocol.ModifyItemPathHandler(ModifyItemPath);
    ServiceProtocol.DeleteItemHandler deleteItem = new ServiceProtocol.DeleteItemHandler(DeleteItem);

    ServiceProtocol.CreateLinkHandler createLink = new ServiceProtocol.CreateLinkHandler(CreateLink);
    ServiceProtocol.ModifyLinkHandler modifyLink = new ServiceProtocol.ModifyLinkHandler(ModifyLink);
    ServiceProtocol.DeleteLinkHandler deleteLink = new ServiceProtocol.DeleteLinkHandler(DeleteLink);

    ServiceProtocol.CreateThingHandler createThing = new ServiceProtocol.CreateThingHandler(CreateThing);
    ServiceProtocol.ModifyThingHandler modifyThing = new ServiceProtocol.ModifyThingHandler(ModifyThing);
    ServiceProtocol.ModifyThingPathHandler modifyThingPath = new ServiceProtocol.ModifyThingPathHandler(ModifyThingPath);
    ServiceProtocol.DeleteThingHandler deleteThing = new ServiceProtocol.DeleteThingHandler(DeleteThing);

    ServiceProtocol.PortCheckHandler portCheck = new ServiceProtocol.PortCheckHandler(PortCheck);

    ServiceProtocol.PropertyListHandler propertyListCheck = new ServiceProtocol.PropertyListHandler(PropertyListCheck);


    serviceProtocol = new ServiceProtocol(changeState, getPropertyValues, getSubTags, createItem, modifyItem, modifyItemPath, deleteItem, createLink, modifyLink, deleteLink, createThing, modifyThing, modifyThingPath, deleteThing, portCheck, propertyListCheck);

    //String filename = PrjName(); //gs_pPrj.

    RemotingServices.Marshal(serviceProtocol, filename);
    m_Config.ProjectList.Add(filename);
    LogNote("Srvr", 0, "Added project %s to ProjectList.", filename);
  }
コード例 #19
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
  bool ModifyItemBoundingRect(ServiceProtocol serviceProtocol, Int64 requestID, Guid guid, RectangleF boundingRect)
  {
    if (true) // Decide whether to modify an item.
    { // We're going to do it.
      // Modify the item.

      // Raise event(s).
      serviceProtocol.DoItemBoundingRectModified(requestID, guid, boundingRect);

      return true;
    }
    else
    { // We're not going to do it.
      return false;
    }
  }
コード例 #20
0
        public async Task TestServiceConnectionWithErrorApplicationTask()
        {
            using (StartVerifiableLog(out var loggerFactory, LogLevel.Warning, expectedErrors: c => true,
                                      logChecker: logs =>
            {
                Assert.Equal(2, logs.Count);
                Assert.Equal("SendLoopStopped", logs[0].Write.EventId.Name);
                Assert.Equal("ApplicationTaskFailed", logs[1].Write.EventId.Name);
                return(true);
            }))
            {
                var            ccm                 = new TestClientConnectionManager();
                var            ccf                 = new ClientConnectionFactory();
                var            protocol            = new ServiceProtocol();
                TestConnection transportConnection = null;
                var            connectionFactory   = new TestConnectionFactory(conn =>
                {
                    transportConnection = conn;
                    return(Task.CompletedTask);
                });
                var services          = new ServiceCollection();
                var errorTcs          = new TaskCompletionSource <Exception>();
                var connectionHandler = new ErrorConnectionHandler(errorTcs);
                services.AddSingleton(connectionHandler);
                var builder = new ConnectionBuilder(services.BuildServiceProvider());

                builder.UseConnectionHandler <ErrorConnectionHandler>();
                ConnectionDelegate handler = builder.Build();

                var connection = new ServiceConnection(protocol, ccm, connectionFactory, loggerFactory, handler, ccf,
                                                       "serverId", Guid.NewGuid().ToString("N"), null, null);

                var connectionTask = connection.StartAsync();

                // completed handshake
                await connection.ConnectionInitializedTask.OrTimeout();

                Assert.Equal(ServiceConnectionStatus.Connected, connection.Status);
                var clientConnectionId = Guid.NewGuid().ToString();

                await transportConnection.Application.Output.WriteAsync(
                    protocol.GetMessageBytes(new OpenConnectionMessage(clientConnectionId, new Claim[] { })));

                var clientConnection = await ccm.WaitForClientConnectionAsync(clientConnectionId).OrTimeout();

                errorTcs.SetException(new InvalidOperationException("error operation"));

                await clientConnection.LifetimeTask.OrTimeout();

                // Should complete the connection when application throws
                await ccm.WaitForClientConnectionRemovalAsync(clientConnectionId).OrTimeout();

                // Application task should not affect the underlying service connection
                Assert.Equal(ServiceConnectionStatus.Connected, connection.Status);

                // complete reading to end the connection
                transportConnection.Application.Output.Complete();

                await connectionTask.OrTimeout();

                Assert.Equal(ServiceConnectionStatus.Disconnected, connection.Status);
                Assert.Empty(ccm.ClientConnections);
            }
        }
コード例 #21
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
  bool ModifyLink(ServiceProtocol serviceProtocol, Int64 requestID, Guid guid, String tag, String classID, Guid origin, Guid destination, String originPort, String destinationPort, List<PointF> controlPoints)
  {
    if (true) // Decide whether to modify an link.
    { // We're going to do it.
      // Modify the item.

      // Raise event(s).
      serviceProtocol.DoLinkModified(requestID, guid, tag, classID, origin, destination, originPort, destinationPort, controlPoints);

      return true;
    }
    else
    { // We're not going to do it.
      return false;
    }
  }
コード例 #22
0
        public async Task <IServiceHubContext> CreateHubContextAsync(string hubName, ILoggerFactory loggerFactory = null, CancellationToken cancellationToken = default)
        {
            loggerFactory = loggerFactory ?? NullLoggerFactory.Instance;
            switch (_serviceManagerOptions.ServiceTransportType)
            {
            case ServiceTransportType.Persistent:
            {
                var connectionFactory                 = new ManagementConnectionFactory(_productInfo, new ConnectionFactory(_serverNameProvider, loggerFactory));
                var serviceProtocol                   = new ServiceProtocol();
                var clientConnectionManager           = new ClientConnectionManager();
                var clientConnectionFactory           = new ClientConnectionFactory();
                ConnectionDelegate connectionDelegate = connectionContext => Task.CompletedTask;
                var serviceConnectionFactory          = new ServiceConnectionFactory(
                    serviceProtocol,
                    clientConnectionManager,
                    connectionFactory,
                    loggerFactory,
                    connectionDelegate,
                    clientConnectionFactory,
                    new DefaultServerNameProvider()
                    );
                var weakConnectionContainer = new WeakServiceConnectionContainer(
                    serviceConnectionFactory,
                    _serviceManagerOptions.ConnectionCount,
                    new HubServiceEndpoint(hubName, _endpointProvider, _endpoint),
                    loggerFactory?.CreateLogger(nameof(WeakServiceConnectionContainer)) ?? NullLogger.Instance);

                var serviceCollection = new ServiceCollection();
                serviceCollection.AddSignalRCore();
                serviceCollection.AddSingleton <IConfigureOptions <HubOptions>, ManagementHubOptionsSetup>();

                if (loggerFactory != null)
                {
                    serviceCollection.AddSingleton(typeof(ILoggerFactory), loggerFactory);
                }

                serviceCollection
                .AddLogging()
                .AddSingleton(typeof(IConnectionFactory), sp => connectionFactory)
                .AddSingleton(typeof(HubLifetimeManager <>), typeof(WebSocketsHubLifetimeManager <>))
                .AddSingleton(typeof(IServiceConnectionManager <>), typeof(ServiceConnectionManager <>))
                .AddSingleton(typeof(IServiceConnectionContainer), sp => weakConnectionContainer);

                var             success         = false;
                ServiceProvider serviceProvider = null;
                try
                {
                    serviceProvider = serviceCollection.BuildServiceProvider();

                    var serviceConnectionManager = serviceProvider.GetRequiredService <IServiceConnectionManager <Hub> >();
                    serviceConnectionManager.SetServiceConnection(weakConnectionContainer);
                    _ = serviceConnectionManager.StartAsync();

                    // wait until service connection established
                    await weakConnectionContainer.ConnectionInitializedTask.OrTimeout(cancellationToken);

                    var webSocketsHubLifetimeManager = (WebSocketsHubLifetimeManager <Hub>)serviceProvider.GetRequiredService <HubLifetimeManager <Hub> >();

                    var hubContext        = serviceProvider.GetRequiredService <IHubContext <Hub> >();
                    var serviceHubContext = new ServiceHubContext(hubContext, webSocketsHubLifetimeManager, serviceProvider);
                    success = true;
                    return(serviceHubContext);
                }
                finally
                {
                    if (!success)
                    {
                        serviceProvider?.Dispose();
                    }
                }
            }

            case ServiceTransportType.Transient:
            {
                var serviceCollection = new ServiceCollection();
                serviceCollection.AddSignalRCore();

                // remove default hub lifetime manager
                var serviceDescriptor = serviceCollection.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(HubLifetimeManager <>));
                serviceCollection.Remove(serviceDescriptor);

                // add rest hub lifetime manager
                var restHubLifetimeManager = new RestHubLifetimeManager(_serviceManagerOptions, hubName, _productInfo);
                serviceCollection.AddSingleton(typeof(HubLifetimeManager <Hub>), sp => restHubLifetimeManager);

                var serviceProvider = serviceCollection.BuildServiceProvider();
                var hubContext      = serviceProvider.GetRequiredService <IHubContext <Hub> >();
                return(new ServiceHubContext(hubContext, restHubLifetimeManager, serviceProvider));
            }

            default:
                throw new ArgumentException("Not supported service transport type.");
            }
        }
コード例 #23
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
  bool ModifyLinkControlPoints(ServiceProtocol serviceProtocol, Int64 requestID, Guid guid, List<PointF> controlPoints)
  {
    if (true) // Decide whether to modify an item.
    { // We're going to do it.
      // Modify the item.

      // Raise event(s).
      serviceProtocol.DoLinkControlPointsModified(requestID, guid, controlPoints);

      return true;
    }
    else
    { // We're not going to do it.
      return false;
    }
  }
コード例 #24
0
        /// <summary> 获取服务 </summary>
        /// <param name="provider"></param>
        /// <param name="type"></param>
        /// <param name="protocol"></param>
        /// <returns></returns>
        public static object GetService(this IServiceProvider provider, Type type, ServiceProtocol protocol)
        {
            var list = provider.GetServices(type);

            return(list.First(t => t.GetType().GetCustomAttribute <ProtocolAttribute>()?.Protocol == protocol));
        }
コード例 #25
0
ファイル: NetServer.cs プロジェクト: ChrisMoreton/Test3
  bool ModifyThing(ServiceProtocol serviceProtocol, Int64 requestID, Guid guid, String tag, String path, RectangleF boundingRect, String xaml, Single angle, bool mirrorX, bool mirrorY)
  {
    if (true) // Decide whether to modify an Thing.
    { // We're going to do it.
      // Modify the Thing.

      // Raise event(s).
      serviceProtocol.DoThingModified(requestID, guid, tag, path, boundingRect, xaml, angle, mirrorX, mirrorY);

      return true;
    }
    else
    { // We're not going to do it.
      return false;
    }
  }
コード例 #26
0
        internal static ServiceHubDispatcher PrepareAndGetDispatcher(IAppBuilder builder, HubConfiguration configuration, ServiceOptions options, string applicationName, ILoggerFactory loggerFactory)
        {
            // Ensure we have the conversions for MS.Owin so that
            // the app builder respects the OwinMiddleware base class
            SignatureConversions.AddConversions(builder);

            // ServiceEndpointManager needs the logger
            var hubs = GetAvailableHubNames(configuration);

            // Get the one from DI or new a default one
            var router = configuration.Resolver.Resolve <IEndpointRouter>() ?? new DefaultEndpointRouter();

            var serverNameProvider = configuration.Resolver.Resolve <IServerNameProvider>();

            if (serverNameProvider == null)
            {
                serverNameProvider = new DefaultServerNameProvider();
                configuration.Resolver.Register(typeof(IServerNameProvider), () => serverNameProvider);
            }

            var synchronizer = configuration.Resolver.Resolve <IAccessKeySynchronizer>();

            if (synchronizer == null)
            {
                synchronizer = new AccessKeySynchronizer(serverNameProvider, loggerFactory);
                configuration.Resolver.Register(typeof(IAccessKeySynchronizer), () => synchronizer);
            }

            var endpoint = new ServiceEndpointManager(synchronizer, options, loggerFactory);

            configuration.Resolver.Register(typeof(IServiceEndpointManager), () => endpoint);

            var requestIdProvider = configuration.Resolver.Resolve <IConnectionRequestIdProvider>();

            if (requestIdProvider == null)
            {
                requestIdProvider = new DefaultConnectionRequestIdProvider();
                configuration.Resolver.Register(typeof(IConnectionRequestIdProvider), () => requestIdProvider);
            }

            builder.Use <NegotiateMiddleware>(configuration, applicationName, endpoint, router, options, serverNameProvider, requestIdProvider, loggerFactory);

            builder.RunSignalR(configuration);

            // Fetch the trace manager from DI and add logger provider
            var traceManager = configuration.Resolver.Resolve <ITraceManager>();

            if (traceManager != null)
            {
                loggerFactory.AddProvider(new TraceManagerLoggerProvider(traceManager));
            }

            configuration.Resolver.Register(typeof(ILoggerFactory), () => loggerFactory);

            // TODO: Using IOptions looks wierd, thinking of a way removing it
            // share the same object all through
            var serviceOptions = Options.Create(options);

            // For safety, ALWAYS register abstract classes or interfaces
            // Some third-party DI frameworks such as Ninject, implicit self-binding concrete types:
            // https://github.com/ninject/ninject/wiki/dependency-injection-with-ninject#skipping-the-type-binding-bit--implicit-self-binding-of-concrete-types
            configuration.Resolver.Register(typeof(IOptions <ServiceOptions>), () => serviceOptions);

            var serviceProtocol = new ServiceProtocol();

            configuration.Resolver.Register(typeof(IServiceProtocol), () => serviceProtocol);

            // allow override from tests
            var scm = configuration.Resolver.Resolve <IServiceConnectionManager>();

            if (scm == null)
            {
                scm = new ServiceConnectionManager(applicationName, hubs);
                configuration.Resolver.Register(typeof(IServiceConnectionManager), () => scm);
            }

            var ccm = configuration.Resolver.Resolve <IClientConnectionManager>();

            if (ccm == null)
            {
                ccm = new ClientConnectionManager(configuration, loggerFactory);
                configuration.Resolver.Register(typeof(IClientConnectionManager), () => ccm);
            }

            var atm = new AzureTransportManager(configuration.Resolver);

            configuration.Resolver.Register(typeof(ITransportManager), () => atm);

            var parser = new SignalRMessageParser(hubs, configuration.Resolver, loggerFactory.CreateLogger <SignalRMessageParser>());

            configuration.Resolver.Register(typeof(IMessageParser), () => parser);

            var smb = new ServiceMessageBus(configuration.Resolver, loggerFactory.CreateLogger <ServiceMessageBus>());

            configuration.Resolver.Register(typeof(IMessageBus), () => smb);

            var scf = configuration.Resolver.Resolve <IServiceConnectionFactory>();

            if (scf == null)
            {
                var connectionFactory = new ConnectionFactory(serverNameProvider, loggerFactory);
                scf = new ServiceConnectionFactory(serviceProtocol, ccm, connectionFactory, loggerFactory, serverNameProvider);
                configuration.Resolver.Register(typeof(IServiceConnectionFactory), () => scf);
            }

            var sccf = new ServiceConnectionContainerFactory(scf, endpoint, router, options, loggerFactory);

            if (hubs?.Count > 0)
            {
                return(new ServiceHubDispatcher(hubs, scm, sccf, serviceOptions, loggerFactory));
            }
            else
            {
                loggerFactory.CreateLogger <DispatcherHelper>().Log(LogLevel.Warning, "No hubs found.");
                return(null);
            }
        }
コード例 #27
0
ファイル: SensorFactory.cs プロジェクト: mriedmann/oom
 public static void RegisterSensorBuilder <T>(ServiceProtocol protocol, Func <ServiceFileRecord, ISensor> builder) where T : ISensor
 {
     store.Add(protocol, builder);
 }