Home > Software engineering >  How to add Startup.cs in existing project .net5
How to add Startup.cs in existing project .net5

Time:02-04

I have an .net5 project and in .csproj file I have this:

  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

I added Microsoft.EntityFrameworkCore package to my prject.furturemore I created Dbcontext file like below:

using Domian;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;


namespace Mc2.CrudTest.Presentation.Front.Infrastructure
{
        public class DataContext : DbContext
        {
            protected readonly IConfiguration Configuration;

            public DataContext(IConfiguration configuration)
            {
                Configuration = configuration;
            }

            protected override void OnConfiguring(DbContextOptionsBuilder options)
            {
                // connect to sql server with connection string from app settings
                options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection"));
            }

            public DbSet<Customer> Customers { get; set; }
        }
    
}

since there wasn't any startup.cs file in my project ,I created one this way: enter image description here

the namespaces of IApplicationBuilder and IWebHostEnvironment coudn't find. I dont know whether I can use startup.cs file like.net core.3.1 or I shouldn't use startup.cs file in .net5 anymore.

And my program.cs file was formed this way:

    using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace Mc2.CrudTest.Presentation.Front
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            WebAssemblyHostBuilder builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");

            builder.Services.AddScoped(_ => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

            await builder.Build().RunAsync();

            builder.Services.AddDbContext(options => options
    
        }
    }
}

In addtion my project is BlazorWebAssembly

CodePudding user response:

First of all, don't use .NET 5. It reached End-of-Life on May 2022. That's almost a year ago. EOL means no support at all, for anything, from either Microsoft or NuGet authors. Not even security patches.

It was known from the start this would be a single-year or "Standard-Term" Support version (STS), supported only for 18 months. The Long-Term-Support version is .NET 6, supported until November 2024. LTS versions are supported for 3 years since release.

Second, you don't need Startup.cs in .NET 6 (or .NET 5). The methods found in Startup.cs were merged into Program.cs. You can write :

builder.Services.AddDbContext(options=>options
    .UseSqlServer(builder.Configuration.GetConnectionString("SqlServerConnection")));

This is shown in all ASP.NET Core and EF Core tutorials, eg this Web API tutorial. In this tutorial, Program.cs contains :

using Microsoft.EntityFrameworkCore;
using TodoApi.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddDbContext<TodoContext>(opt =>
    opt.UseInMemoryDatabase("TodoList"));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Notice that even Program.Main is missing. That's the entire file. This is possible through a few new C# features: top-level statements and implied usings.

If you don't like this style you can use --use-program-main to generate a Program.cs and Main method

CodePudding user response:

First off, of course you should update to .NET6 or .NET7 if you can[1]. But if that's not practical for whatever reason, then of course you can use startup.cs. In fact I prefer to as well, out of habit (you can use it in .NET6 too; not sure about 7 but I assume so).

You can define startup.cs more or less the way you do, but you do need the right using's:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;

Less obviously, in your program.cs you need

 using Microsoft.AspNetCore;

 ...

 public static async Task Main(string[] args)
 {
      ...
      WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
      ...
 }

[1] Microsoft IMO has done the world a disservice with its post-Framework policy of introducing breaking changes into each ASP.NET version so liberally. It's not always just a matter of retargeting. And that's especially true of Blazor which is still so immature. Certainly if security is a concern for this application you should be doing everything you can to upgrade, but in the real world isn't always that simple.

  • Related