.NET Hosting 不支持 IStartup。

huangapple go评论65阅读模式
英文:

.NET Hosting IStartup isn't supported

问题

这是我的当前 Program 类:

using System.Net;
using System.Text;
using DatingApp.API.Data;
using DatingApp.API.Helpers;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

namespace DatingApp.API
{
    class Program
    {
        public static void Main(string[] args)
        {

            var builder = WebApplication.CreateBuilder(args);

            // 将服务添加到容器中

            builder.Services.AddControllers();
            // 了解有关配置 Swagger/OpenAPI 的更多信息,请访问 https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            builder.Services.AddDbContext<DataContext>(options =>
            {
                options.UseSqlServer("DefaultConnection");
            });

            builder.Services.AddCors(x => x.AddPolicy("corsapp", builder =>
                {
                    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                }));

            builder.Services.AddScoped<IAuthRepository, AuthRepository>();
            builder.Services.AddScoped<IDatingRepository, DatingRepository>();

            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8
                        .GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                });

            var app = builder.Build();

            var host = CreateWebHostBuilder(args).Build();
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService<DataContext>();
                    context.Database.Migrate();
                    Seed.SeedUsers(context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "迁移发生错误");
                }
            }

            // 配置 HTTP 请求管道
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            else
            {
                app.UseExceptionHandler(builder =>
                {
                    builder.Run(async context =>
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        var error = context.Features.Get<IExceptionHandlerFeature>();
                        if (error != null)
                        {
                            context.Response.addApplicationError(error.Error.Message);
                            await context.Response.WriteAsync(error.Error.Message);
                        }
                    });
                });
            }

            app.UseRouting();

            app.UseCors("corsapp");

            app.UseAuthentication();

            app.UseAuthorization();

            app.MapControllers();

            app.Run();

            host.Run();

        }

        public static IHostBuilder CreateWebHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<StartupBase>();
                });
    }
}

这是错误信息:

未处理的异常。System.NotSupportedException: 不支持 Microsoft.AspNetCore.Hosting.IStartup
在 Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services, Object instance)
在 Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass14_0.b__0(HostBuilderContext context, IServiceCollection services)
在 Microsoft.Extensions.Hosting.HostBuilder.InitializeServiceProvider()
在 Microsoft.Extensions.Hosting.HostBuilder.Build()
在 DatingApp.API.Program.Main(String[] args) in D:\Demo\DatingApp\datingapp.api\Program.cs:line 54

它应该运行并将数据迁移到数据库,但未能运行。

英文:

This is my current Program class:

using System.Net;
using System.Text;
using DatingApp.API.Data;
using DatingApp.API.Helpers;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

namespace DatingApp.API
{
    class Program
    {
        public static void Main(string[] args)
        {

            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            builder.Services.AddDbContext&lt;DataContext&gt;(options =&gt;
            {
                options.UseSqlServer(&quot;DefaultConnection&quot;);
            });

            builder.Services.AddCors(x =&gt; x.AddPolicy(&quot;corsapp&quot;, builder =&gt;
                {
                    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                }));

            builder.Services.AddScoped&lt;IAuthRepository, AuthRepository&gt;();
            builder.Services.AddScoped&lt;IDatingRepository, DatingRepository&gt;();

            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =&gt;
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8
                        .GetBytes(builder.Configuration.GetSection(&quot;AppSettings:Token&quot;).Value)),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                });

            var app = builder.Build();

            var host = CreateWebHostBuilder(args).Build();
            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    var context = services.GetRequiredService&lt;DataContext&gt;();
                    context.Database.Migrate();
                    Seed.SeedUsers(context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService&lt;ILogger&lt;Program&gt;&gt;();
                    logger.LogError(ex, &quot;An error occurred in migration&quot;);
                }
            }



            // Configure the HTTP request pipeline. 
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            else
            {
                app.UseExceptionHandler(builder =&gt;
                {
                    builder.Run(async context =&gt;
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        var error = context.Features.Get&lt;IExceptionHandlerFeature&gt;();
                        if (error != null)
                        {
                            context.Response.addApplicationError(error.Error.Message);
                            await context.Response.WriteAsync(error.Error.Message);
                        }
                    });
                });
            }

            // app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors(&quot;corsapp&quot;);

            app.UseAuthentication();

            app.UseAuthorization();

            app.MapControllers();

            app.Run();

            host.Run();

        }

    public static IHostBuilder CreateWebHostBuilder(string[] args) =&gt;
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =&gt;
                {
                    webBuilder.UseStartup&lt;StartupBase&gt;();
                });
    }
}

Here is the error:

>Unhandled exception. System.NotSupportedException: Microsoft.AspNetCore.Hosting.IStartup isn't supported
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services, Object instance)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass14_0.<UseStartup>b__0(HostBuilderContext context, IServiceCollection services)
at Microsoft.Extensions.Hosting.HostBuilder.InitializeServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at DatingApp.API.Program.Main(String[] args) in D:\Demo\DatingApp\datingapp.api\Program.cs:line 54

It is supposed to run and migrate the data to the database but it didn't run

答案1

得分: 1

不需要创建主机和使用启动项,只需从 app.Services 创建范围:

using (var scope = app.Services.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService&lt;DataContext&gt;();
    // 使用上下文
}

至于 IStartup - 也可以查看这个答案

英文:

There is no need to create host and use startup, just create scope from the app.Services:

using(var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService&lt;DataContext&gt;();
// use context
}

As for IStartup - check also this answer.

huangapple
  • 本文由 发表于 2023年7月27日 20:56:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76779965.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定