我正在try 使用.NET6创建我自己的Web API,但在将数据放入数据库之前,我收到了一个错误

System.InvalidOperationException:‘无法创建类型为’Hotelum.HotelsSeeder‘的实例,因为无法绑定一个或多个参数.构造函数参数必须具有相应的属性.不支持字段.缺少的属性为:‘dbContext’

using Hotelum.Entities;
using Microsoft.EntityFrameworkCore;

namespace Hotelum
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddTransient<IWeatherForecastService, WeatherForecastService>();
            builder.Services.AddControllers();
            builder.Services.AddDbContext<HotelsDbContext>();
            builder.Services.AddScoped<HotelsSeeder>();

            var app = builder.Build();

            // Configure the HTTP request pipeline.

            app.Configuration.Get<HotelsSeeder>(); //Error appears
            HotelsSeeder seeder = app.Services.GetRequiredService<HotelsSeeder>(); 
            seeder.Seed();
            
            app.UseHttpsRedirection();

            //app.UseAuthorization();

            app.MapControllers();

            app.Run();
        }
    }
}

我一直在寻找任何解决方案,但都找不到.

下面是数据所在的类

using Hotelum.Entities;

namespace Hotelum
{
    public class HotelsSeeder
    {
        private readonly HotelsDbContext _dbContext;

        public HotelsSeeder(HotelsDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public void Seed()
        {
            if (_dbContext.Database.CanConnect())
            {
                if (!_dbContext.Hotels.Any())
                {
                    var hotel = GetHotels();
                    _dbContext.Hotels.AddRange(hotel);
                    _dbContext.SaveChanges();
                }
            }
        }

        private IEnumerable<Hotels> GetHotels()
        {
            var hotel = new List<Hotels>();
            new Hotels()
            {
                Name = "Avocado",
                Description = "Perfect for family, chill and drinks",
                Category = "Holidays",
                IsItOpen = true,
                ContactEmail = "contact@avocado.com",
                ContactNumber = "123456789",
                Rooms = new List<Rooms>()
                {
                    new Rooms()
                    {
                        Name = "Król",
                        Description = "Dla bogatych",
                        Price = 8549098M,
                        NumberOfRooms = 1,
                    },
                    new Rooms()
                    {
                        Name = "Królowa",
                        Description = "Dla mniej bogatych",
                        Price = 89098M,
                        NumberOfRooms = 5,
                    },
                    new Rooms()
                    {
                        Name = "Standart",
                        Description = "Dla standartów",
                        Price = 88M,
                        NumberOfRooms = 25,
                    },
                },
                Address = new Address()
                {
                    City = "Wwa",
                    Street = "Poznanska",
                    PostalCode = "10-092"
                }
            };
            new Hotels()
            {
                Name = "Abada",
                Description = "Perfect for horrors",
                Category = "Horros",
                IsItOpen = true,
                ContactEmail = "contact@abada.com",
                ContactNumber = "123456789",
                Rooms = new List<Rooms>
                {
                    new Rooms()
                    {
                        Name = "Bieda",
                        Description = "Dla odważnych",
                        Price = 8M,
                        NumberOfRooms = 1,
                    },
                    new Rooms()
                    {
                        Name = "Mniejsza bieda",
                        Description = "Dla normalnych",
                        Price = 98M,
                        NumberOfRooms = 5,
                    },
                    new Rooms()
                    {
                        Name = "Bogato",
                        Description = "Dla bogatych",
                        Price = 88M,
                        NumberOfRooms = 25,
                    }
                },
                Address = new Address()
                {
                    City = "Poznan",
                    Street = "Warszawska",
                    PostalCode = "50-792"
                }
            };
            return hotel;
        }
    }
}

我试图用配置来实现它,但找不到一种方法来使用它,我试图为它添加AddDbContext,也不起作用.

推荐答案

这里有几件事不对劲,首先是你的Program.cs岁.您应该正确使用DI

using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    try
    {
        var seeder = services.GetRequiredService<HotelsSeeder>();
        seeder.Seed();
    }
    catch (Exception ex)
    {
        // Handle any exceptions while seeding
        Console.WriteLine($"An error occurred while seeding the database: {ex.Message}");
    }
}

HotelsSeeder应当在申请范围内从服务Provider 处解决.using语句用于确保在完成对.seed()的调用后正确处置作用域.

在您的方法GetHotels()中,您没有将Hotels个对象添加到要设定种子的列表hotel中.

 private IEnumerable<Hotels> GetHotels()
 {
     var hotel = new List<Hotels> {
     new Hotels()
     {
         Name = "Avocado",
         Description = "Perfect for family, chill and drinks",
         Category = "Holidays",
         IsItOpen = true,
         ContactEmail = "contact@avocado.com",
         ContactNumber = "123456789",
         Rooms = new List<Rooms>()
         {
             new Rooms()
             {
                 Name = "Król",
                 Description = "Dla bogatych",
                 Price = 8549098M,
                 NumberOfRooms = 1,
             },
             new Rooms()
             {
                 Name = "Królowa",
                 Description = "Dla mniej bogatych",
                 Price = 89098M,
                 NumberOfRooms = 5,
             },
             new Rooms()
             {
                 Name = "Standart",
                 Description = "Dla standartów",
                 Price = 88M,
                 NumberOfRooms = 25,
             },
         },
         Address = new Address()
         {
             City = "Wwa",
             Street = "Poznanska",
             PostalCode = "10-092"
         }
     },
     new Hotels()
     {
         Name = "Abada",
         Description = "Perfect for horrors",
         Category = "Horros",
         IsItOpen = true,
         ContactEmail = "contact@abada.com",
         ContactNumber = "123456789",
         Rooms = new List<Rooms>
         {
             new Rooms()
             {
                 Name = "Bieda",
                 Description = "Dla odważnych",
                 Price = 8M,
                 NumberOfRooms = 1,
             },
             new Rooms()
             {
                 Name = "Mniejsza bieda",
                 Description = "Dla normalnych",
                 Price = 98M,
                 NumberOfRooms = 5,
             },
             new Rooms()
             {
                 Name = "Bogato",
                 Description = "Dla bogatych",
                 Price = 88M,
                 NumberOfRooms = 25,
             }
         },
         Address = new Address()
         {
             City = "Poznan",
             Street = "Warszawska",
             PostalCode = "50-792"
         }
     }};
     return hotel;
 }

Additional

我看不到这里添加了连接字符串: builder.Services.AddDbContext<HotelsDbContext>();

要么将其添加到此处,要么将其添加到覆盖方法OnConfiguring下的HotelsDbContext

Csharp相关问答推荐

禁用AutoSuggestBox项目更改时的动画?

注册通用工厂的C# Dep注入

处理. netstandard2.0项目中HttpClient.SslProtocol的PlatformNotSupportedException问题""

为什么我的ASP.NET核心MVC应用程序要为HTML元素添加一些标识符?

C#.NET依赖项注入顺序澄清

XUNIT是否使用测试数据的源生成器?

Rider将.NET安装在哪里

C#-从基类更新子类

尽管保证密钥不同,但已添加相同密钥的项(&Q;)

如何在WPF的树视图中显示一个对象的两个或多个属性,其中只有一个是分层项?

使用Dapper映射联接查询对象数据到使用SplitOn;

如何使用MailKit删除邮箱?

如何将DotNet Watch与发布配置和传递给应用程序的参数一起使用?

.NET 8 DI GetServices<;对象&>不工作

获取混淆&Quot;模糊引用&Quot;错误

类/值和日期的泛型方法

Xamarin中出错.表单:应用程序的分部声明不能指定不同的基类

.NET EF Core Automapper项目到筛选不起作用

实体框架允许您具有筛选的属性吗?

LINQ在GROUP BY和JOIN之后获取子列表