【发布时间】:2016-12-17 19:11:34
【问题描述】:
我正在尝试创建一个服务,该服务将作为 Windows 服务运行,如 here 所述。我的问题是示例 Web 主机服务构造函数仅采用 IWebHost 参数。我的服务需要一个更像这样的构造函数:
public static class HostExtensions
{
public static void RunAsMyService(this IWebHost host)
{
var webHostService =
new MyService(host, loggerFactory, myClientFactory, schedulerProvider);
ServiceBase.Run(webHostService);
}
}
我的Startup.cs 文件与此类似:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.AddInMemoryCollection();
this.Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
this.container.RegisterSingleton<IConfiguration>(this.Configuration);
services.AddSingleton<IControllerActivator>(
new SimpleInjectorControllerActivator(container));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
app.UseSimpleInjectorAspNetRequestScoping(this.container);
this.container.Options.DefaultScopedLifestyle = new AspNetRequestLifestyle();
this.InitializeContainer(app, loggerFactory);
this.container.Verify();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
}
private void InitializeContainer(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
container.Register(() => loggerFactory, Lifestyle.Singleton);
container.Register<IMyClientFactory>(() => new MyClientFactory());
container.Register<ISchedulerProvider>(() => new SchedulerProvider());
}
显然,我使用 Simple Injector 作为 DI 容器。它在IServiceCollection 注册,详见their documentation。
我的问题是如何在 HostExtensions 类中访问框架的容器(IServicesCollection),以便将必要的依赖项注入MyService?对于 MVC 控制器,这一切都只是在幕后处理,但我不知道任何详细说明如何在其他地方需要的地方访问它的文档。
【问题讨论】:
-
我很好奇,当 .Net Core 附带的一个 (
IServiceCollection) 工作正常时,为什么还要使用另一个 DI 容器?这似乎添加了一个完全没有必要的层。有什么优势吗? -
@R.Richards 内置容器不太适合构建围绕 SOLID 原则构建的大型应用程序,正如 here 所解释的那样。
标签: c# dependency-injection asp.net-core simple-injector