Missing Startup.cs in .NET 6, how to configure?


Hello, I have started using Visual Studio 2022 and Was trying to create a new ASP.NET Core (.NET 6) project, but when I tried to add new JSON settings in Startup.cs, I wasn't able to found this file? So How can i configure JSON settings or database context details in .NET 6 without startup.cs


Asked by:- neena
1
: 2815 At:- 5/13/2022 12:40:15 PM
ASP.NET Core Missing Startup.cs







1 Answers
profileImage Answered by:- vikas_jk

In new .NET 6, Startup.cs is merged with Program.cs so now you can use all the configuration in Program.cs something like this to add JSON Settings (After installing Nuget package 'Microsoft.AspNetCore.Mvc.NewtonsoftJson' for it)

using Newtonsoft.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddControllers().AddNewtonsoftJson(options =>
{
    // Use the default property (Pascal) casing
    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});

Also, if you want to add database connection string you can have something like this

builder.Services.AddDbContext<DBContextHere>

instead of old way "services.AddDbContext"

To Add Services in .NET 6 Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add the memory cache services.
builder.Services.AddMemoryCache();

// Add a custom scoped service.
builder.Services.AddScoped<ITodoRepository, TodoRepository>();
var app = builder.Build();

To Add Custom dependency injection (DI) container in .NET 6

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

// Register services directly with Autofac here. Don't
// call builder.Populate(), that happens in AutofacServiceProviderFactory.
builder.Host.ConfigureContainer<ContainerBuilder>(builder => builder.RegisterModule(new MyApplicationModule()));

var app = builder.Build();

Here is the complete migration guide

https://docs.microsoft.com/en-us/aspnet/core/migration/50-to-60?view=aspnetcore-5.0&tabs=visual-studio#where-do-i-put-state-that-was-stored-as-fields-in-my-program-or-startup-class

With sample and comparison of code from old to new .net version (6)

https://docs.microsoft.com/en-us/aspnet/core/migration/50-to-60-samples?view=aspnetcore-5.0

Hope it helps.

1
At:- 5/13/2022 12:57:25 PM
Excellent answer, thanks for adding useful links. 0
By : neena - at :- 5/13/2022 12:59:25 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use