【发布时间】:2014-04-06 17:32:27
【问题描述】:
我正在尝试将 SignalR 2 引入现有项目,其中所有依赖项注入都使用 autofac 执行,所有依赖项配置都在 Global.asax 中执行。我找到了 Autofac.SignalR 包,用于将 SignalR 与 autofac 及其 accompanying documentation 一起使用。
我遵循了提供的文档中的示例,并遵循了使用 RegisterHubs 函数而不是定义我的个人集线器依赖项的建议。
不幸的是,我的 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;
我也按照例子设置了我的hub类:
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>();
【问题讨论】:
标签: asp.net-mvc dependency-injection signalr autofac signalr-hub