在ASP.NET5控制台应用程序中使用Startup类 [英] Using Startup class in ASP.NET5 Console Application

查看:730
本文介绍了在ASP.NET5控制台应用程序中使用Startup类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible for an ASP.NET 5-beta4 console application (built from the ASP.NET Console project template in VS2015) to use the Startup class to handle registering services and setting up configuration details?

我已经尝试创建一个典型的Startup类,但是当通过dnx . run或在Visual Studio 2015中运行控制台应用程序时,似乎从未调用过它.

I've tried to create a typical Startup class, but it never seems to be called when running the console application via dnx . run or inside 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<Settings>(Configuration.GetSubKey("Settings"));

    services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<ApplicationContext>(options => options.UseSqlServer(this.Configuration["Data:DefaultConnection:ConnectionString"]));
  }

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  {
    loggerFactory.AddConsole(minLevel: LogLevel.Warning);
  }
}

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

I've tried to manually create the Startup class in my Main method, but this doesn't seem like the right solution and hasn't so far allowed me to configure the services.

我假设我可以通过某种方法来创建HostingContext,该HostingContext不能启动Web服务器,但可以使控制台应用程序保持活动状态.类似于:

I'm assuming there's some way for me to create a HostingContext that doesn't start up a web server but will keep the console application alive. Something along the lines of:

HostingContext context = new HostingContext()
{
  ApplicationName = "AppName"
};

using (new HostingEngine().Start(context))
{
  // console code
}

到目前为止,使此功能正常工作的唯一方法是将HostingContext.ServerFactoryLocation设置为Microsoft.AspNet.Server.WebListener,这将启动Web服务器.

However so far the only way I can get this to work is if I set the HostingContext.ServerFactoryLocation to Microsoft.AspNet.Server.WebListener, which starts up the web server.

推荐答案

您正在寻找正确的主意,但我认为您需要备份一下.

What you're looking for is the right idea, but I think you'll need to back up a moment.

首先,您可能已经注意到默认的Program类不再使用静态方法.这是因为构造函数实际上独立地获得了一些依赖注入爱!

Firstly, you may have noticed that your default Program class isn't using static methods anymore; this is because the constructor actually gets some dependency injection love all on its own!

public class Program
{
    public Program(IApplicationEnvironment env)
    {            
    }        

    public void Main(string[] args)
    {
    }
}

不幸的是,注册ASP.NET 5托管环境所使用的服务并不多.感谢本文IServiceManifest,您可以看到只有几种服务可用:

Unfortunately, there aren't as many of the services you're used to from an ASP.NET 5 hosting environment registered; thanks to this article and the IServiceManifest you can see that there's only a few services available:

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

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

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

This means you'll get the joy of creating your own service provider, too, since we can't get the one provided by the framework.

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中拥有想要使用的服务提供商.

This takes away a lot of the magic that you see in the standard ASP.NET 5 projects, and now you have the service provider you wanted available to you in your Main.

这里还有更多的陷阱",所以我不妨列出来:

There's a few more "gotchas" in here, so I might as well list them out:

  • 如果您要求输入IHostingEnvironment,则该字段将为null.那是因为托管环境来自ASP.Net 5托管.
  • 由于您没有其中之一,因此您将没有IHostingEnvironment.EnvironmentName-您需要自己从环境变量中收集它.由于您已经将其加载到Configuration对象中,因此应该不会有问题. (它的名称是"ASPNET_ENV",您可以在项目设置的调试"选项卡中添加它;默认情况下,控制台应用程序未为您设置此名称.无论如何,您可能都想重命名该名称,因为您实际上并没有不再谈论ASPNET环境.)
  • If you ask for an IHostingEnvironment, it'll be null. That's because a hosting environment comes from, well, ASP.Net 5 hosting.
  • Since you don't have one of those, you'll be left without your IHostingEnvironment.EnvironmentName - you'll need to collect it from the environment variables yourself. Which, since you're already loading it into your Configuration object, shouldn't be a problem. (It's name is "ASPNET_ENV", which you can add in the Debug tab of your project settings; this is not set for you by default for console applications. You'll probably want to rename that, anyway, since you're not really talking about an ASPNET environment anymore.)

这篇关于在ASP.NET5控制台应用程序中使用Startup类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆