Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Startup class in ASP.NET5 Console Application

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?

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 is pretty much:

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);
  }
}

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.

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
}

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.

like image 478
sixones Avatar asked May 15 '15 10:05

sixones


People also ask

How is the startup class useful in asp net?

The Startup class ASP.NET Core apps use a Startup class, which is named Startup by convention. The Startup class: Optionally includes a ConfigureServices method to configure the app's services. A service is a reusable component that provides app functionality.

How do I register a class in startup NET Core?

The name "Startup" is by ASP.NET Core convention. However, we can give any name to the Startup class, just specify it as the generic parameter in the UseStartup<T>() method. For example, to name the Startup class as MyStartup, specify it as . UseStartup<MyStartup>() .

Which method of startup class configures or adds services required by the application?

The startup class contains two methods: ConfigureServices and Configure. Declaration of this method is not mandatory in startup class. This method is used to configure services that are used by the application. When the application is requested for the first time, it calls ConfigureServices method.

What is startup cs in ASP.NET Core?

The Startup class contains the ConfigureServices and Configure methods. While the former is used to configure the required services, the latter is used to configure the request processing pipeline. The Configure method is executed immediately after the ConfigureServices method.

What is startup class in ASP NET 5?

Startup class is the entry point of ASP.NET 5 application like Global.asax in an earlier version of ASP.NET. Application may have more than one startup class but ASP.NET will handle such a situation gracefully. Startup class is mandatory in ASP.NET 5 application.

Is ASP NET Core a console app?

Yes, it is. ASP.NET Core applications can either be self-hosted - as in your example - or hosted inside a web server such as IIS. In.NET Core all apps are console apps.

How to configure services in startup class in Visual Studio?

Open Startup class in Visual Studio by clicking on the Startup.cs in the solution explorer. The following is a default Startup class in ASP.NET Core 2.x. As you can see, Startup class includes two public methods: ConfigureServices and Configure . The Startup class must include a Configure method and can optionally include ConfigureService method.

What is the startup class in NET Core?

.Net Core Startup Class Guide. The Startup class is a single place to… | by Sukhpinder Singh | C# Programming | Medium The Startup class is a single place to configure services and the app's request pipeline. It contains an optional Configure Services method to configure app services. A service is a reusable module that provides functionality.


1 Answers

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

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)
    {
    }
}

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

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)
{
}

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:

  • 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.)
like image 119
Matt DeKrey Avatar answered Sep 17 '22 17:09

Matt DeKrey