我正在尝试让 SignalR 与 Autofac 一起工作。我有一个我在这里所做的精简版本的存储库:
https://github.com/justsayno/signalr-autofac
这是改编自使用的作品GlobalHost
:
https://github.com/sstorie/experiments/tree/master/angular2-signalr
使用 GlobalHost 对象效果很好。我尝试按照 Autofac 网站上有关如何注入 SignalR 服务的文档进行操作,但我无法让它工作。这是我用于注册依赖项的配置文件:
public static IContainer RegisterDependencies()
{
// Create your builder.
var builder = new ContainerBuilder();
//register controllers in DI
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// Register SignalR hubs
builder.RegisterHubs(Assembly.GetExecutingAssembly());
return builder.Build();
}
我从startup.cs 中调用它:
public class Startup
{
public static IContainer Container { get; set; }
public void Configuration(IAppBuilder app)
{
var config = GlobalConfiguration.Configuration;
// configure IoC container
Container = AutofacConfiguration.RegisterDependencies();
//set dependency resolver from WebAPI and MVC
config.DependencyResolver = new AutofacWebApiDependencyResolver(Container);
DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(Container));
//register Autofac Middleware
app.UseAutofacMiddleware(Container);
app.Map("/signalr", a =>
{
a.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
Resolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(Container)
};
a.RunSignalR(hubConfiguration);
});
// This server will be accessed by clients from other domains, so
// we open up CORS
//
app.UseCors(CorsOptions.AllowAll);
// Build up the WebAPI middleware
//
var httpConfig = new HttpConfiguration();
httpConfig.MapHttpAttributeRoutes();
app.UseWebApi(httpConfig);
}
}
我有一个控制器,它已将其注入到其构造函数中:
public TaskController(IHubContext hubContext)
{
// Commented out hard coded global host version
//
//_context = GlobalHost.ConnectionManager.GetHubContext<EventHub>();
// using DI
_context = hubContext;
}
然而,这给了我一个关于控制器没有默认构造函数的错误(所以我认为这是我的 IHubContext 未找到的问题)。
任何帮助都会很棒。我已经对我正在谈论的内容做了一个存储库,可以在这里找到完整的解决方案:
https://github.com/justsayno/signalr-autofac