我正在尝试使用Autofac解决不同类的接口的不同实现,原因是我想通过我的消息处理程序中的SignalR集线器向客户端发送更新 - 但是我不想要处理程序成为集线器客户端本身,不同的处理程序需要使用不同的集线器。
我最初看起来像这样:
public class Hub1 : Hub { }
public class Hub2 : Hub { }
public class Handler1 : IHandle<Message1>
{
private AppData data;
private IHubContext hubContext;
public Handler1(AppData data)
{
this.data = data;
this.hubContext = GlobalHost.ConnectionManager.GetHubContext<Hub1>()
}
}
public class Handler2 : IHandle<Message2>
{
private AppData data;
private IHubContext hubContext;
public Handler2(AppData data)
{
this.data = data;
this.hubContext = GlobalHost.ConnectionManager.GetHubContext<Hub2>()
}
}
使用Autofac绑定如下:
// Single shared instance of AppData for all handlers
builder.RegisterType<AppData>().AsSelf().SingleInstance();
builder.RegisterType<Handler1>().AsImplementedInterfaces();
builder.RegisterType<Handler2>().AsImplementedInterfaces();
这两个处理程序已经通过Autofac注入了AppData
,但我还想注入IHubContext
,但我正在努力弄清楚如何去做。
我已更改为要求IHubContext
作为处理程序中的构造函数参数:
public class Handler1 : IHandle<Message1>
{
private AppData data;
private IHubContext hubContext;
public Handler1(AppData data, IHubContext hubContext)
{
this.data = data;
this.hubContext = hubContext;
}
}
我已尝试将IHubContext
注册为命名服务并指定处理程序的注册,如下所示:
builder.Register<IHubContext>(_ => GlobalHost.ConnectionManager.GetHubContext<Hub1>())
.Named<IHubContext>("Hub1Context");
builder.Register<IHubContext>(_ => GlobalHost.ConnectionManager.GetHubContext<Hub2>())
.Named<IHubContext>("Hub2Context");
builder.RegisterType<Handler1>()
.WithParameter(ResolvedParameter.ForNamed<IHubContext>("Hub1Context"));
builder.RegisterType<Handler2>()
.WithParameter(ResolvedParameter.ForNamed<IHubContext>("Hub2Context"));
然而,这会导致异常:
A first chance exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll
Additional information: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Handler1' can be invoked with the available services and parameters:
Cannot resolve parameter 'Microsoft.AspNet.SignalR.IHubContext hubContext' of constructor 'Void .ctor(AppData, Microsoft.AspNet.SignalR.IHubContext)'.
我哪里错了?我在过去和Ninject做过类似的事情,只是说了一句话:
kernel.Bind<IHubContext>()
.ToMethod(_ => GlobalHost.ConnectionManager.GetHubContext<Hub1>())
.WhenInjectedInto<Handler1>();