C# 使用Autofac解决接口的不同实现

C# 使用Autofac解决接口的不同实现,c#,dependency-injection,autofac,C#,Dependency Injection,Autofac,我正在尝试使用Autofac解决不同类接口的不同实现,原因是我希望通过消息处理程序中的信号集线器向客户端发送更新-但是我不希望处理程序本身是集线器客户端,不同的处理程序需要使用不同的集线器 我最初的想法是这样的: public class Hub1 : Hub { } public class Hub2 : Hub { } public class Handler1 : IHandle<Message1> { private AppData data; privat

我正在尝试使用Autofac解决不同类接口的不同实现,原因是我希望通过消息处理程序中的信号集线器向客户端发送更新-但是我不希望处理程序本身是集线器客户端,不同的处理程序需要使用不同的集线器

我最初的想法是这样的:

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>()
    }
}
我已尝试将
IHubContext
注册为命名服务,并按如下方式指定处理程序的注册:

// Single shared instance of AppData for all handlers
builder.RegisterType<AppData>().AsSelf().SingleInstance();

builder.RegisterType<Handler1>().AsImplementedInterfaces();
builder.RegisterType<Handler2>().AsImplementedInterfaces();
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"));
我哪里做错了?我在过去对Ninject做过类似的事情,只是说了一些大致的话:

kernel.Bind<IHubContext>()
      .ToMethod(_ => GlobalHost.ConnectionManager.GetHubContext<Hub1>())
      .WhenInjectedInto<Handler1>();
kernel.Bind()
.ToMethod(=>GlobalHost.ConnectionManager.GetHubContext())
.当输入到()时;

看起来您需要将属性公开或在构造函数中要求IHubContext。@Victor我已经让构造函数接受了
IHubContext
,问题是Autofac不知道如何解决它(根据例外情况),您是在映射集线器之前还是之后设置Autofac容器(当SignalR初始化时)? 您需要在Signal r之前设置容器。@Quackmatic-它们是同时设置的,我有一个调用
builder.registerubs(…)
的过程发生在上面的注册码之后-不确定为什么会有区别?@TrevorPilley:嘿!你解决那个问题了吗??
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)'.
kernel.Bind<IHubContext>()
      .ToMethod(_ => GlobalHost.ConnectionManager.GetHubContext<Hub1>())
      .WhenInjectedInto<Handler1>();