【发布时间】:2021-06-21 18:44:48
【问题描述】:
我在运行代码时不断收到此错误:
System.AggregateException:'无法构造某些服务(验证服务描述符时出错'ServiceType:LykoDemo.Data.BookingService Lifetime:Scoped ImplementationType:LykoDemo.Data.BookingService':无法解析类型的服务' LykoDemo.Data.LykoDemo.LykosqlContext' 同时尝试激活'LykoDemo.Data.BookingService'。)'
内部异常 1:
InvalidOperationException:验证服务描述符“ServiceType:LykoDemo.Data.BookingService Lifetime:Scoped ImplementationType:LykoDemo.Data.BookingService”时出错:尝试激活时无法解析“LykoDemo.Data.LykoDemo.LykosqlContext”类型的服务'LykoDemo.Data.BookingService'。
内部异常 2:
InvalidOperationException:尝试激活“LykoDemo.Data.BookingService”时无法解析“LykoDemo.Data.LykoDemo.LykosqlContext”类型的服务。
从数据库中获取列表:
public class BookingService
{
private readonly LykosqlContext _context;
public BookingService(LykosqlContext context)
{
_context = context;
}
public async Task<List<Booking>> GetBookingsAsync(string strCurrentUser)
{
return await _context.Booking
.Where(x => x.UserName == strCurrentUser)
.AsNoTracking().ToListAsync();
}
public async Task<List<Room>> GetRoomsAsync()
{
return await _context.Room.ToListAsync();
}
}
获取列表到我的页面:
@code {
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
List<Booking> bookings;
List<Room> rooms;
protected override async Task OnInitializedAsync()
{
var user = (await authenticationStateTask).User;
rooms = await Service.GetRoomsAsync();
bookings = await Service.GetBookingsAsync(user.Identity.Name);
}
}
在我的 Startup.cs 中我添加了:
services.AddScoped<BookingService>();
如果我删除
services.AddScoped<BookingService>();
它运行,但我无法访问该页面。但是如果我删除它并且
rooms = await Service.GetRoomsAsync();
bookings = await Service.GetBookingsAsync(user.Identity.Name);
一切运行顺利,但我显然无法从数据库中填充我的列表。我确定我只是犯了一些新手错误,但感谢您提供任何帮助。
编辑:
我的 startup.cs 如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
services.AddSingleton<WeatherForecastService>();
services.AddScoped<BookingService>();
}
【问题讨论】:
-
添加服务。AddScoped
();到您的 ConfigureServices(IServiceCollection services) 方法。
标签: c# asp.net-core blazor