.NET 6 WebAPI中HotelsSeeder实例创建失败,提示参数无法绑定
错误信息
System.InvalidOperationException: 'Cannot create instance of type 'Hotelum.HotelsSeeder' because one or more parameters cannot be bound to. Constructor parameters must have corresponding properties. Fields are not supported. Missing properties are: 'dbContext'
问题原因
你在Program.cs里调用了app.Configuration.Get<HotelsSeeder>();,这个方法是从配置文件(如appsettings.json)读取配置并绑定类实例,完全不依赖依赖注入(DI)容器。但HotelsSeeder的构造函数需要HotelsDbContext参数,配置文件里没有对应配置项,所以触发错误。而且你已经通过app.Services.GetRequiredService<HotelsSeeder>()从DI容器获取实例,这行代码完全多余。
另外GetHotels方法存在逻辑漏洞:你new了两个Hotels对象,但没有将它们添加到hotel列表中,导致Seed执行时不会向数据库插入任何数据。
解决方案
1. 移除错误的配置绑定代码
直接删掉Program.cs中的这一行:
app.Configuration.Get<HotelsSeeder>(); //Error appears
修改后的Program.cs关键代码:
var app = builder.Build(); // Configure the HTTP request pipeline. HotelsSeeder seeder = app.Services.GetRequiredService<HotelsSeeder>(); seeder.Seed(); app.UseHttpsRedirection(); // ... 其他代码
2. 修复GetHotels方法的数据添加逻辑
在GetHotels方法中,把new出来的Hotels对象添加到hotel列表中:
修改后的GetHotels方法:
private IEnumerable<Hotels> GetHotels() { var hotel = new List<Hotels>(); // 添加第一个酒店 hotel.Add(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" } }); // 添加第二个酒店 hotel.Add(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; }
额外说明
- 你已经正确将
HotelsDbContext和HotelsSeeder注册到DI容器,通过app.Services.GetRequiredService<HotelsSeeder>()可以正常获取带有注入HotelsDbContext的实例。 - 确保
HotelsDbContext配置正确,能正常连接数据库,否则Seed方法中的_dbContext.Database.CanConnect()会返回false,不会执行数据插入。
内容的提问来源于stack exchange,提问作者Insikt

