Wednesday, November 1, 2017

ASP.NET Core 2.0: Why it’s important to have Program.BuildWebHost method?

I was doing some refactoring on an ASP.NET Core 2.0 Web Application which was migrated from ASP.NET Core 1.1.

In ASP.NET Core 1.1 Web Applications, program.cs was like this.
public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();
 
        host.Run();
    }
}
But with ASP.NET Core 2.0, it has to be something like this.
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 felt like I can eliminate BuildWebHost method, so I did like follows.
public class Program
{
    public static void Main(string[] args)
    {
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build()
            .Run();
    }
}
All seem be good, the application was running well. After sometime, I wanted to add a database migration, and when I tried to do Add-Migration, I was getting this weird error.
Unable to create an object of type 'T'. Add an implementation of 'IDesignTimeDbContextFactory<T>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
Apparently the error turned out to be program.cs not having BuildWebHost method.

In ASP.NET Core 1.x to ASP.NET Core 2.0 Migration Guide, it specifically says, “The adoption of this new 2.0 pattern is highly recommended and is required for product features like Entity Framework (EF) Core Migrations to work.”

Once I added it back, I was able to add database migrations back again.

Lesson learnt: When doing refactoring, somethings are better left alone!

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment