在自托管应用程序中使用 SignalR 2.0,来自 these instructions你有这样的东西:
class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR(new HubConfiguration { Resolver = ... });
}
}
class Program
{
static void Main(string[] args)
{
using (WebApp.Start("http://localhost:8080")) // constructs Startup instance internally
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
}
您会注意到 Startup 类实例是使用一些幕后魔法创建的。我不知道如何填写对它的依赖关系。有什么方法可以覆盖 Startup 类的构造,以便我可以将依赖项注入(inject)其中吗?
最佳答案
无需替换 IAppActivator,您只需将 Startup 的构造函数参数注册到 Katana 的 ServiceProvider。
默认的 IAppActivator 将为您解析与 Startup 构造函数的参数类型相匹配的任何服务。唯一的缺点是您不能使用 WebApp.Start,因为它不会公开 ServiceProvider:
public class MyService : IMyService
{
private readonly IMyOtherService _myOtherService;
// Services will be recursively resolved by Katana's ServiceProvider
public MyService(IMyOtherService myOtherService)
{
_myOtherService = myOtherService;
}
// Implementation
}
public class Startup
{
private readonly IMyService _myService;
// Startup must have exactly one constructor.
public Startup(IMyService myService)
{
_myService = myService
}
public void Configuration(IAppBuilder app)
{
app.MapSignalR(new HubConfiguration { Resolver = ... });
}
}
using System;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.Hosting.Services;
using Microsoft.Owin.Hosting.Starter;
public class Program
{
static void Main(string[] args)
{
var url = "http://localhost:8080";
var services = (ServiceProvider)ServicesFactory.Create();
var options = new StartOptions(url);
services.Add<IMyOtherService, MyOtherService>();
services.Add<IMyService, MyService>();
var starter = services.GetService<IHostingStarter>();
using (starter.Start(options)) // constructs Startup instance internally
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
}
我将 WebApp.Start 的默认实现复制到 Program.Main 中,但我没有立即调用 IHostingStarter.Start,而是先添加自定义服务:http://katanaproject.codeplex.com/SourceControl/changeset/view/c726b87e90c05677a256ca1821bac481f402d6bd#src/Microsoft.Owin.Hosting/WebApp.cs
ServiceProvider 还有许多其他重载。如果需要,请添加:http://msdn.microsoft.com/en-us/library/microsoft.owin.hosting.services.serviceprovider(v=vs.111).aspx
这应该比我在之前的回答中建议的那样使用 StartOptions.Settings 替换 Katana 的 IAppActivator 简单得多。
但是,我将保留我之前的回答,因为它确实更详细地解释了 Startup 类的构造方式以及如何使用 Settings 字典替换默认服务实现。
关于c# - 在 Signalr 2.0 自托管中使用依赖注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21389081/