私は次のコードを持っています:
[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がハブから派生する必要があります。HがTestHubタイプである場合、問題はないはずですが、その構文は機能していません。
どうすればこれを機能させることができますか?
私の解決策(リフレクションを使用)
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 });
});
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加