在MVC 5应用程序中使用autofac in为SignalR Hub注入依赖关系

时间:2014-03-04 22:29:39

标签: asp.net-mvc dependency-injection signalr autofac signalr-hub

我正在尝试将SignalR 2引入现有项目,其中使用autofac执行所有依赖项注入,并且所有依赖项配置都在Global.asax中执行。我找到了使用带有autofac的SignalR及其accompanying documentation的Autofac.SignalR软件包。

我按照提供的文档中的示例进行操作,并遵循使用RegisterHubs函数的建议,而不是定义我的各个集线器依赖项。

不幸的是,在尝试从lifetimeScope

中解析依赖项时,我的Hub类会出现以下运行时错误
Autofac.Core.DependencyResolutionException was unhandled by user code
HResult=-2146233088
Message=No scope with a Tag matching 'AutofacWebRequest' is
visible from the scope in which instance was requested.
This generally indicates that a component registered as per-HTTP
request is being requested by a SingleInstance() component
(or a similar scenario.) Under the web integration always request
dependencies from the DependencyResolver.Current or 
ILifetimeScopeProvider.RequestLifetime, never from the container itself.

我无法让DependencyResolver.Current或ILifeTimeScopeProvider为我工作。

我的依赖配置如下

var builder = new ContainerBuilder();
    .RegisterControllers(typeof (MvcApplication).Assembly);
    .RegisterHubs(Assembly.GetExecutingAssembly());
    ...
var container = builder.Build();

// Set dependency resolver for MVC
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

// Set dependency resolver for Web API
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

// Set the dependency resolver for SignalR
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

var signalRDependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);
GlobalHost.DependencyResolver = signalRDependencyResolver;

我还根据示例设置了我的集线器类:

public class BaseHub : Hub
{
    protected readonly ILifetimeScope _hubLifetimeScope;
    private static IUserSignalRConnectionRepository _userSignalRConnectionRepository;

    public BaseHub(ILifetimeScope lifetimeScope) : base()
    {
        _hubLifetimeScope = lifetimeScope.BeginLifetimeScope();

        _userSignalRConnectionRepository = _hubLifetimeScope.Resolve<IUserSignalRConnectionRepository>();
    }

    protected override void Dispose(bool disposing)
    {
        // Dipose the hub lifetime scope when the hub is disposed.
        if (disposing && _hubLifetimeScope != null)
            _hubLifetimeScope.Dispose();

        base.Dispose(disposing);
    }
}

中的cub类中发生异常
_userSignalRConnectionRepository = _hubLifetimeScope.Resolve<IUserSignalRConnectionRepository>();

1 个答案:

答案 0 :(得分:5)

您应该包含注册IUserSignalRConnectionRepository的代码。

错误消息似乎表明此依赖项是使用等同于InstancePerHttpRequest()的{​​{1}}注册的。在MVC请求的情况下,此范围是自动创建的,但对于SignalR请求则不会自动创建(这可能是一件好事,因为它们可以无限期地持续)。

您可以通过致电InstancePerMatchingLifetimeScope("AutofacWebRequest")解决此问题。而不是你的Hub构造函数中的lifetimeScope.BeginLifetimeScope("AutofacWebRequest");

或者,您可以使用lifetimeScope.BeginLifetimeScope();(默认值)或InstancePerDependency()而不是SingleInstance()注册IUserSignalRConnectionRepository。