Unable to run my ASP.NET application after upgrading to .NET 7

175 Views Asked by At

I have upgraded my ASP.NET MVC 2.2 application to ASP.NET Core 7 MVC, but my application is not running. Below is my startup.cs file. What did I do wrong?

public IServiceProvider ConfigureServices(IServiceCollection services)
{ 
    services
          .AddAntiforgery(options => options.HeaderName = "XSRF-TOKEN")
          .AddControllers(options =>
          {
              options.CacheProfiles.Add("DefaultNoCacheProfile", new CacheProfile
              {
                  NoStore = true,
                  Location = ResponseCacheLocation.None
              });
              options.Filters.Add(new ResponseCacheAttribute
              {
                  CacheProfileName = "DefaultNoCacheProfile"
              });

    var sp = services.BuildServiceProvider(); 
    /* Here getting a Warning ASP0000 Calling 'BuildServiceProvider' 
       from application code results in an additional copy 
       of singleton services being created. 
       Consider alternatives such as dependency injecting 
       services as parameters to 'Configure' */

    return sp;
}

public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
      // app.UseSession();
      
      app.UseAuthentication();

      if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();
      }
      else
      {
          app.UseExceptionHandler("/Home/Error");
      }

      app.UseMiddleware<HttpRequestWare>(_container);
      app.UseStaticFiles();

      app.UseCookiePolicy(new CookiePolicyOptions
      {
          MinimumSameSitePolicy = SameSiteMode.Strict,
      });

      var environment = _config["Environment"];

      if (environment == EnvironmentType.Live.ToString())
      {
          var supportedCultures = new[]
          {
              new CultureInfo("en-US")
          };
          app.UseRequestLocalization(new RequestLocalizationOptions
          {
              SupportedCultures = supportedCultures,
              SupportedUICultures = supportedCultures,
              RequestCultureProviders = new List<IRequestCultureProvider> {
                  new AcceptLanguageHeaderRequestCultureProvider()
              }
          });
      }

     //app.UseMvc();
      app.UseRouting();
      app.UseEndpoints(endpoints => {
          endpoints.MapDefaultControllerRoute();
          endpoints.MapControllerRoute("default", "{controller=Account}/{action=login}/{id?}");
          endpoints.MapControllerRoute("api", "{controller}/{action}/{id?}");
      });
}

The warning that I have been getting:

Warning ASP0000 Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created.
Consider alternatives such as dependency injecting services as parameters to 'Configure'

1

There are 1 best solutions below

0
On

Do not call .BuildServiceProvider() as this creates instances of all your singleton scoped services, in .Net 7 the builder middleware calls this for us later, which means that there will be duplicates of your Singleton services, which you probably do not want ;)


Migrating from .Net Framework to .Net 7 is a big jump, many namespaces have changed or entirely new constructs exist for solving DI and deployment issues. The good news is that most of the functional changes are in the application initialization.

If you are reading this but looking for migration from .Net Core 2.2 you should start at the Migration guides, specifically [Migrate from ASP.NET Core 2.2 to 3.0][1]

In .Net 6 the Minimal Hosting Model was introduced, this is probably the biggest fundamental shift, appart from .Net Core web apps being their own executable, which is why initialization is different. I encourage you to embrace the new framework and migrate away from StartUp. Even though it is a bit old, the [Porting existing ASP.NET Apps to .NET 6 e-book (PDF)][2] is a well curated guide to the both the implementation and theory needed to migrate your code and mind to .Net Core.

You can also use the .NET Upgrade Assistant as explained here: Upgrade from ASP.NET MVC and Web API to ASP.NET Core MVC

The minimal startup for your app might look something like this, in Program.cs:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAntiforgery(options => options.HeaderName = "XSRF-TOKEN")
                .AddMvc(options =>
                {
                    options.CacheProfiles.Add("DefaultNoCacheProfile", new CacheProfile
                    {
                        NoStore = true,
                        Location = ResponseCacheLocation.None
                    });
                    options.Filters.Add(new ResponseCacheAttribute
                    {
                        CacheProfileName = "DefaultNoCacheProfile"
                    });
                });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();

Notice we don't actually call BuildServiceProvider(), that is nested deep within builder.Build()