这是我提供的课程
[AttributeUsage(AttributeTargets.Method)]
internal class HubClientProxyAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
internal class HubServerProxyAttribute : Attribute { }
public static partial class HubConnectionExtensions
{
[HubClientProxy]
public static partial IDisposable Subscribe<T>(this HubConnection connection, T provider);
[HubServerProxy]
public static partial T HubInvoker<T>(this HubConnection connection);
}
它正在生成这些文件
HubClientProxy.g.cs
public static partial class HubConnectionExtensions
{
public static partial System.IDisposable Subscribe<T>(this HubConnection connection, T provider)
{
if (provider is null)
{
throw new System.ArgumentNullException("provider");
}
throw new System.ArgumentException(nameof(T)); // this line seems wrong, we should have code here.
}
private sealed class CallbackProviderRegistration : System.IDisposable
{
private System.IDisposable[]? registrations;
public CallbackProviderRegistration(params System.IDisposable[] registrations)
{
this.registrations = registrations;
}
public void Dispose()
{
if (this.registrations is null)
{
return;
}
System.Collections.Generic.List<System.Exception>? exceptions = null;
foreach(var registration in this.registrations)
{
try
{
registration.Dispose();
}
catch (System.Exception exc)
{
if (exceptions is null)
{
exceptions = new ();
}
exceptions.Add(exc);
}
}
this.registrations = null;
if (exceptions is not null)
{
throw new System.AggregateException(exceptions);
}
}
}
}
HubServerProxy.g.cs
public static partial class HubConnectionExtensions
{
public static partial T HubInvoker<T>(this HubConnection connection)
{
throw new System.ArgumentException(nameof(T)); // this line seems wrong, we should have code here.
}
}
我是这样使用的,AppService继承了与hub相同的接口,并且它抛出异常
public AppService(IHttpClientFactory clientFactory, ILogger<AppService> logger)
{
_logger = logger;
_client = clientFactory.CreateClient("clientname");
_hub = new HubConnectionBuilder().WithUrl($"{_client.BaseAddress!.GetLeftPart(UriPartial.Authority)}/hubpath").Build();
_subscriber = _hub.Subscribe(this); // exception
_dataTaskSource = InitializeDataTaskSource();
}
我尝试为扩展方法指定不同的名称,也许我必须使用特定的名称?源生成器似乎接受任何方法名称。
public AppService(IHttpClientFactory clientFactory, ILogger<AppService> logger)
{
_logger = logger;
_client = clientFactory.CreateClient("clientname");
_hub = new HubConnectionBuilder().WithUrl($"{_client.BaseAddress!.GetLeftPart(UriPartial.Authority)}/hubpath").Build();
_subscriber = _hub.Subscribe<ICompleteNotifier>(this); // exception
_dataTaskSource = InitializeDataTaskSource();
}
我必须显式地将接口放入通用扩展方法调用中。仅当它是一个接口时才有效。