我有一个SignalR 2项目,它也使用WebApi,我试图将AutoFac集成到这个项目中。
最初,我的Startup类看起来像这样:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.MapSignalR();
var httpConfig = new HttpConfiguration();
httpConfig.MapHttpAttributeRoutes();
app.UseWebApi(httpConfig);
}
}
没有使用autofac,一切正常。现在,我尝试添加AutoFac,因此我将Startup类更改为如下所示:
public void Configuration(IAppBuilder app)
{
var builder = new ContainerBuilder();
var httpConfig = new HttpConfiguration();
var hubConfig = new HubConfiguration();
// Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterHubs(Assembly.GetExecutingAssembly());
var container = builder.Build();
httpConfig.DependencyResolver = new AutofacWebApiDependencyResolver(container);
hubConfig.Resolver = new AutofacDependencyResolver(container);
app.UseAutofacMiddleware(container);
app.MapSignalR("/signalr", hubConfig);
app.UseWebApi(httpConfig);
}
现在发生的事情是我无法拨打我的控制器,因为每次拨打电话时都会收到404电话。我错过了什么?在web api的autofac快速入门指南中,有一个app.UseAutofacWebApi(config)的调用,但是,该方法不存在,因此,不确定是否存在问题或者是什么。
答案 0 :(得分:1)
我有同样的问题。对我来说,我必须单独添加集线器并使用Nuget Packages Autofac.SignalR 3.0.2版和SignalR.Extras.Autofac v1.2.0。有几个Autofac SignalR软件包,确保它只是那两个。
虽然我也改变了其他一些东西。这就是我做到的。 var builder = new ContainerBuilder();
// REGISTER CONTROLLERS SO DEPENDENCIES ARE CONSTRUCTOR INJECTED
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// Register the SignalR hubs.
builder.RegisterType<UpdateHub>().ExternallyOwned();
builder.RegisterType<NotificationHub>().ExternallyOwned();
// BUILD THE CONTAINER
var container = builder.Build();
// Configure SignalR with an instance of the Autofac dependency resolver.
GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container);
DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container);
// REGISTER WITH OWIN
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
app.MapSignalR();
ConfigureAuth(app);
我做的另一个错误是认为集线器本身可以注入控制器。你不能这样做,所以如果你需要通过集线器上下文,我需要找到一种方法来注入集线器上下文。这是我的待办事项。
var updateHubContext = GlobalHost.ConnectionManager.GetHubContext<UpdateHub>();
updateHubContext.Clients.All.update();
如果您需要生命周期范围,则必须使用ILifetimeScope接口将依赖关系解析到您的集线器中。您需要注入Lifetime Scope,然后从中解决它们。
private readonly ILifetimeScope _hubLifetimeScope;
private readonly IEntityService<Update> _updateService;
public UpdateHub(ILifetimeScope lifetimeScope)
{
//the AutofacWebRequest is important. It will not work without it
_hubLifetimeScope = lifetimeScope.BeginLifetimeScope("AutofacWebRequest");
_updateService = _hubLifetimeScope.Resolve<IEntityService<Update>>();
}
希望这会有所帮助。 javascript与网站上的教程相同。没有什么改变。