如何在C#

时间:2019-04-19 08:37:08

标签: c# signalr

我有以下代码:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
    public class SignalRHub : Attribute
    {
        public readonly string Route;

        public SignalRHub(string Route)
        {
            this.Route = Route;
        }
    }

    [SignalRHub("hubpath")]
    public class TestHub : Hub
    {
        ...
    }

这定义了一个SignalR集线器,该集线器具有一个知道路径的属性。

我想用SignalRHub属性动态注册集线器,所以我有以下代码来查找所有集线器:

        // find all hubs
        var Hubs =
            from Assemblies in AppDomain.CurrentDomain.GetAssemblies().AsParallel()
            from Types in Assemblies.GetTypes()
            let Attributes = Types.GetCustomAttributes(typeof(SignalRHub), true)
            where Attributes?.Length > 0
            select new { Type = Types };

        var HubsList = Hubs.ToList();

然后我要注册它们,但这是我遇到的问题:

        foreach (var H in HubsList)
        {
            // get the route attribute
            var Route = string.Empty;
            var Attributes = Attribute.GetCustomAttributes(H.Type);
            foreach (var Attribute in Attributes)
            {
                if (Attribute is SignalRHub A)
                {
                    Route = A.Route;
                    break;
                }
            }

            // register the hub
            if (string.IsNullOrEmpty(Route))
            {
                Logging.Warn($"[Hub] {H.Type.Name} does not have a path, skipping");
            }
            else
            {
                Logging.Info($"[Hub] Registering {H.Type.Name} with path {Route}");
                Application.UseSignalR(R => R.MapHub<H>(Route)); <- this won't compile
            }

MapHub要求T源自Hub;如果H的类型为TestHub,应该没问题,但是该语法无法正常工作。

我该如何做?

2 个答案:

答案 0 :(得分:1)

我的解决方案(使用反射)

using System;
using System.Reflection;
using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Connections;
//somewhere in your code
private static readonly MethodInfo mapperMethodInfo = 
    typeof(HubRouteBuilder).GetMethod(
        "MapHub",
        new Type [] { 
            typeof(PathString)
        },
        null
    );

// in your mapping code
// replace this:
Application.UseSignalR(R => R.MapHub<H>(Route));  

// with this
Application.UseSignalR(R => 
{
   // pay attention to use of H.Type, R and Route variables
   mapperMethodInfo.MakeGenericMethod(H.Type).Invoke(R, new object [] { Route });
});

答案 1 :(得分:0)

编译器不满意,因为您将实例变量用作通用类型。

由于H实例变量指向Hub实例,因此您可以替换:

Application.UseSignalR(R => R.MapHub<H>(Route))

通过:

Application.UseSignalR(R => R.MapHub<Hub>(Route))