在ASP.NET5控制台应用程序中使用Startup类

ASP.NET 5-beta4控制台应用程序(从VS2015中的ASP.NET控制台项目模板构建)是否可以使用Startup类来处理注册服务和设置配置详细信息?

我试图创建一个典型的Startup类,但是在通过dnx . run运行控制台应用程序时似乎永远不会调用它dnx . run dnx . run或在Visual Studio 2015中。

Startup.cs几乎是:

 public class Startup { public Startup(IHostingEnvironment env) { Configuration configuration = new Configuration(); configuration.AddJsonFile("config.json"); configuration.AddJsonFile("config.{env.EnvironmentName.ToLower()}.json", optional: true); configuration.AddEnvironmentVariables(); this.Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { services.Configure(Configuration.GetSubKey("Settings")); services.AddEntityFramework() .AddSqlServer() .AddDbContext(options => options.UseSqlServer(this.Configuration["Data:DefaultConnection:ConnectionString"])); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(minLevel: LogLevel.Warning); } } 

我试图在我的Main方法中手动创建Startup类,但这似乎不是正确的解决方案,到目前为止还没有允许我配置服务。

我假设有一些方法让我创建一个不启动Web服务器但会使控制台应用程序保持活动状态的HostingContext 。 有点像:

 HostingContext context = new HostingContext() { ApplicationName = "AppName" }; using (new HostingEngine().Start(context)) { // console code } 

但是到目前为止,我能够使用它的唯一方法是将HostingContext.ServerFactoryLocation设置为启动Web服务器的Microsoft.AspNet.Server.WebListener

您正在寻找的是正确的想法,但我认为您需要备份一下。

首先,您可能已经注意到您的默认Program类不再使用静态方法了; 这是因为构造函数实际上获得了一些dependency injection爱自己的一切!

 public class Program { public Program(IApplicationEnvironment env) { } public void Main(string[] args) { } } 

不幸的是,您注册的ASP.NET 5托管环境中没有那么多的服务; 感谢本文和IServiceManifest您可以看到只有少数服务可用:

Microsoft.Framework.Runtime.IAssemblyLoaderContainer Microsoft.Framework.Runtime.IAssemblyLoadContextAccessor Microsoft.Framework.Runtime.IApplicationEnvironment Microsoft.Framework.Runtime.IFileMonitor Microsoft.Framework.Runtime.IFileWatcher Microsoft.Framework.Runtime.ILibraryManager Microsoft.Framework.Runtime.ICompilerOptionsProvider Microsoft .Framework.Runtime.IApplicationShutdown

这意味着您也可以获得创建自己的服务提供商的乐趣,因为我们无法获得框架提供的服务提供商。

 private readonly IServiceProvider serviceProvider; public Program(IApplicationEnvironment env, IServiceManifest serviceManifest) { var services = new ServiceCollection(); ConfigureServices(services); serviceProvider = services.BuildServiceProvider(); } private void ConfigureServices(IServiceCollection services) { } 

这会消除您在标准ASP.NET 5项目中看到的许多魔力,现在您可以在Main使用您想要的服务提供程序。

这里还有一些“陷阱”,所以我不妨将它们列出来:

  • 如果你要求IHostingEnvironment ,它将为null。 这是因为托管环境来自ASP.Net 5托管。
  • 由于你没有其中一个,你将没有你的IHostingEnvironment.EnvironmentName – 你需要自己从环境变量中收集它。 其中,因为您已经将它加载到Configuration对象中,所以不应该是一个问题。 (它的名称是“ASPNET_ENV”,您可以在项目设置的“调试”选项卡中添加;默认情况下,这不是为控制台应用程序设置的。无论如何,您可能想要重命名,因为您不是真的再谈谈ASPNET环境。)