.NET6 创建ASP.NET Core MVC 没有 Startup 类、没有 ConfigureServices 方法

以官方文档(教程:在 ASP.NET MVC Web 应用中使用 EF Core 入门)为例,原文地址教程:在 ASP.NET MVC Web 应用中使用 EF Core 入门 | Microsoft Docs

.NET6 创建ASP.NET Core MVC 没有 Startup 类、没有 ConfigureServices 方法_第1张图片

 通过.NET6 创建的ASP.NET Core MVC项目没有没有 Startup 类和ConfigureServices 方法

参考其他项目解决方法如下:

新建一个HostingExtensions类(类名可以自己定义)

HostingExtensions类代码如下(具体代码可视自身情况修改,仅提供思路):

using ContosoUniversity.Data;
using Microsoft.EntityFrameworkCore;

namespace ContosoUniversity
{
    public static class HostingExtensions
    {
        public static WebApplication ConfigureServices(this WebApplicationBuilder builder)
        {
            // Add services to the container.
            builder.Services.AddControllersWithViews();

            //注册 SchoolContext
            builder.Services.AddDbContext(options =>
       options.UseMySql(builder.Configuration.GetConnectionString("MysqlConnection"), new MySqlServerVersion(new Version())));
            //添加数据库异常筛选器
            builder.Services.AddDatabaseDeveloperPageExceptionFilter();

            return builder.Build();
        }

        public static WebApplication ConfigurePipeline(this WebApplication app)
        {
            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/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();

            //初始化数据库
            CreateDbIfNotExists(app);

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            return app;
        }
        /// 
        /// 自定义的方法,初始化数据库
        /// 
        /// 
        private static void CreateDbIfNotExists(IHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    //从依赖注入容器中获取数据库上下文实例。
                    var context = services.GetRequiredService();
                    //调用 DbInitializer.Initialize 方法。当 Initialize 方法完成时释放上下文
                    DbInitializer.Initialize(context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService>();
                    logger.LogError(ex, "An error occurred creating the DB.");
                }
            }
        }
    }
}

修改Program.cs代码

例如:

using ContosoUniversity;

var builder = WebApplication.CreateBuilder(args);



var app = builder
    .ConfigureServices()//HostingExtensions类中添加的方法
    .ConfigurePipeline();//HostingExtensions类中添加的方法



app.Run();

你可能感兴趣的:(.NET,CORE,.net6,mvc,asp.net,.netcore)