Scope error when using Autofac with SignalR

為{幸葍}努か 提交于 2019-12-04 06:31:36

The problem is this line:

builder.RegisterModule(new AutofacWebTypesModule());

The exception message indicates that, during resolution, something is trying to be resolved from a lifetime scope tagged httpRequest. You get registrations like this in Autofac when you register something InstancePerHttpRequest():

// These two are roughly equivalent:
builder.RegisterType<SomeType>().InstancePerHttpRequest();
builder.RegisterType<SomeType>().InstancePerMatchingLifetimeScope("AutofacWebRequest");

If you look at the source of the AutofacWebTypesModule it registers the web abstractions (like HttpContextBase, the thing you're looking for) as InstancePerHttpRequest.

Further, if you look at the way the Autofac.Integration.Mvc.AutofacDependencyResolver works, whenever you resolve a type during a request, it creates a new, nested, named lifetime scope tagged with httpRequest. This allows you to have that magic InstancePerHttpRequest.

Under the assumption the SignalR.Autofac library you're using is the one here, which is also the one on NuGet), looking in the SignalR.Autofac.AutofacDependencyResolver, no such nested/named lifetime scope is being created for service resolution.

Thus, when Autofac tries to resolve the HttpContextBase dependency, it can't find that httpRequest tagged scope (because it doesn't exist) and issues the error you're seeing.

There is no simple answer for this. The nested httpRequest scope is actually important because it basically can't exist outside of a real web request. It makes it "safe" - you can't get an HttpContextBase if there's no web context (say, at application startup).

If you need to inject an HttpContextBase and you're sure that your EventHub will only live for one web request and that's it (I'm no SignalR guy, so bear with me), it means you either need to:

  • Request a fix for this from the SignalR.Autofac project.
  • Implement your own custom SignalR.Autofac.AutofacDependencyResolver that handles things the way the MVC resolver does.

Without actually doing the work and testing it out myself, I can't really provide specific guidance on how to accomplish that. This exercise is left to the reader.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!