C# System.InvalidOperationException:无法解析类型依赖项注入的服务
我正在开发一个web应用程序—托管在ASP.NET上的Blazor WebAssembly。我正在尝试从数据库中获取价值(使用实体框架)。我正在解决方案中使用存储库和UnitOfWork模式。 因此,我面临着这个错误:C# System.InvalidOperationException:无法解析类型依赖项注入的服务,c#,blazor,blazor-server-side,blazor-webassembly,asp.net-blazor,C#,Blazor,Blazor Server Side,Blazor Webassembly,Asp.net Blazor,我正在开发一个web应用程序—托管在ASP.NET上的Blazor WebAssembly。我正在尝试从数据库中获取价值(使用实体框架)。我正在解决方案中使用存储库和UnitOfWork模式。 因此,我面临着这个错误: An unhandled exception has occurred while executing the request. System.InvalidOperationException: Unable to resolve service for type
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Unable to resolve service for type 'ReportApp.Core.Services.TaskService' while attempting to activate 'ReportApp.Server.Controllers.TaskController'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method8(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Builder.Extensions.MapMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
存储库
界面:
public interface ITaskRepository : IGenericRepository<TaskEntity>
{
}
public interface IGenericRepository<TEntity> where TEntity : class
{
Task<TEntity> GetByIdAsync(Int32 id);
Task InsertAsync(TEntity entity);
Task UpdateAsync(TEntity entity);
Task DeleteAsync(Int32 id);
Task<IEnumerable<TEntity>> GetAllAsync();
Task SaveAsync();
}
public class TaskRepository : ITaskRepository
{
private readonly ReportAppContext _context;
public TaskRepository(ReportAppContext context)
{
_context = context;
}
服务器上的服务器和控制器:
[Route("api/[controller]")]
[ApiController]
public class TaskController : ControllerBase
{
private readonly TaskService _taskService;
public TaskController(TaskService taskService)
{
_taskService = taskService;
}
[HttpGet("get-all")]
public async Task<ActionResult<List<TaskDto>>> GetAllTasksAsync()
{
var result = await _taskService.GetAllAsync();
return Ok(result);
}
我尝试添加以下内容:
services.AddTransient<ITaskRepository, TaskRepository>();
services.AddTransient();
与
AddScoped
相同,但它没有改变任何东西…但在TaskController
中,您正在注入TaskService,而不是TaskRepository。我认为您还需要注册TaskService(我假设TaskService使用TaskRepository。两者都可以注册为作用域)
services.AddTransient();或
services.addScope();
services.AddTransient();或
services.addScope();
作用域和瞬态之间的区别在于,当您将服务注册为瞬态时,每次解析时都会返回一个新实例,而作用域将在作用域中返回相同的实例。错误告诉您TaskService未注册,但您的控制器需要它作为注入服务 在ConfigureServices中,尝试以下操作:
services.AddScoped<TaskService>(sp => {
// Build your Context Options
DbContextOptionsBuilder<ReportAppContext> optsBuilder = new DbContextOptionsBuilder<ReportAppContext>();
optsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
// Build your context (using the options from the builder)
ReportAppContext ctx = new ReportAppContext(optsBuilder.options);
// Build your unit of work (and pass in the context)
UnitOfWork uow = new UnitOfWork(ctx);
// Build your service (and pass in the unit of work)
TaskService svc = new TaskService(uow)
// Return your Svc
return svc;
});
services.AddScoped(sp=>{
//构建上下文选项
DbContextOptionsBuilder optsBuilder=新的DbContextOptionsBuilder();
使用SQLServer(Configuration.GetConnectionString(“DefaultConnection”);
//构建上下文(使用生成器中的选项)
ReportAppContext ctx=新的ReportAppContext(optsBuilder.options);
//构建您的工作单元(并在上下文中传递)
工作单位uow=新工作单位(ctx);
//构建您的服务(并传入工作单元)
TaskService svc=新TaskService(uow)
//返回您的Svc
返回svc;
});
然后,您的控制器将收到一个完全配置的TaskService,可供使用
如果愿意,可以将每个项目依次放入DI容器中,但UOW、存储库和上下文不需要在TaskService之外访问,因此这有点浪费时间
只需如上所述创建配置好的TaskService,这就是DI容器需要注入的全部内容。我添加了:
services.AddTransient();services.AddTransient()代码>现在它说:System.aggregateeexception:“有些服务无法构建(验证服务描述符“ServiceType:ReportApp.Core.Services.TaskService生存期:瞬态实现类型:ReportApp.Core.Services.TaskService”时出错:在尝试激活“ReportApp.Core.Services.TaskService”时,无法解析“ReportApp.DAL.Tools.UnitOfWork”类型的服务。)
我认为UnitOfWork不应该继承数据库上下文。只需将tour上下文注入UnitOfWork即可
public void ConfigureServices(IServiceCollection services)
{
var connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<ReportAppContext>(options => options.UseSqlServer(connection));
services.AddCors();
services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });
services.AddControllersWithViews();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/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.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
services.AddTransient<ITaskRepository, TaskRepository>();
services.AddTransient<ITaskRepository, TaskRepository>(); OR
services.AddScoped<ITaskRepository, TaskRepository>();
services.AddTransient<TaskService>(); OR
services.AddScoped<TaskService>();
services.AddScoped<TaskService>(sp => {
// Build your Context Options
DbContextOptionsBuilder<ReportAppContext> optsBuilder = new DbContextOptionsBuilder<ReportAppContext>();
optsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
// Build your context (using the options from the builder)
ReportAppContext ctx = new ReportAppContext(optsBuilder.options);
// Build your unit of work (and pass in the context)
UnitOfWork uow = new UnitOfWork(ctx);
// Build your service (and pass in the unit of work)
TaskService svc = new TaskService(uow)
// Return your Svc
return svc;
});