Reputation: 4775
I am on a Mac using dotnet Core 2.0
I would like to use a different database on my local development machine, like sqlite and SQL Server on staging and production.
I can have the following appsettings.json files: appsettings.Development.json, appsettings.Staging.json, and appsettings.json for development, staging, and production respectively.
In each of the files I want a different database like sqlite for development and SQLServer for staging and production, including different migrations.
My development environment is set to Development via an environment variable. When I run dotnet run I can confirm the hosting environment is Hosting environment: Development
In my program.cs file I have the following code
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
I have a class called StartupDevelopment
public class StartupDevelopment
{
public StartupDevelopment(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<MvcTriviaContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("dbContext")));
}
}
When I debug my application the constructor of the class Starup is called instead of StartupDevelopment.
Now I do not want to change program.cs because then i would have to change that for each environment.
I want the code to use StartupDevelopment when my environment is set to Development.
Documentation says
An alternative to injecting IHostingEnvironment is to use a conventions-based approach. The app can define separate Startup classes for different environments (for example, StartupDevelopment), and the appropriate startup class is selected at runtime.
I don't understand what am I doing wrong? How do I make the app use StartupDevelopment
when my environment is Development.
Upvotes: 0
Views: 297
Reputation: 4775
Instead of using StartupDevelopment it is better to use ConfigureDevelopmentServices method in Startup.cs. This way our program.cs remains untouched and this solution works with dotnet aspen-codegenerator when creating controllers.
Upvotes: 0
Reputation: 40838
I'm on Windows, and I get the same behavior that you are seeing.
What worked was changing UsesStartup<Startup>
to UsesStartup(typeof(Startup).Assembly.FullName)
in Program.cs. The documentation is not clear about this, but I think if you specify a startup type that forces Asp.Net Core to use that type and not use conventions for finding the startup type.
Upvotes: 1