How to perform calculation in ASP.net Core where the calculation method is present in repository and need to call in controller for testing

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

How to perform calculation in ASP.net Core where the calculation method is present in repository and need to call in controller for testing

问题

我正在尝试使用Swagger API执行测试。每当我尝试输入timesheedid时,它会返回错误500。

以下是该方法的代码:

public void ComputeProductivity(long timesheetId)
{
    var timesheet = _artDBContext.Timesheets.FirstOrDefault(x => x.Id == timesheetId);
    if (timesheet != null)
    {
        var percentage = 100;
        var conversionValue = 60;
        var weekValue = 5;
        var totalWorkingHoursPerWeek = 7 / 365;
        timesheet.TotalHoursWorked = Convert.ToDecimal(timesheet.TimesheetDateOut - timesheet.TimesheetDateIn);
        timesheet.ProductivityPerc = timesheet.TotalHoursWorked * percentage; 
        timesheet.ProductivityHr = timesheet.ProductivityMin / conversionValue;
        timesheet.ProductivityMin = timesheet.TotalHoursWorked * conversionValue;
        timesheet.FTERatio = (timesheet.TotalHoursWorked * weekValue) / (timesheet.TotalHoursWorked * totalWorkingHoursPerWeek );

        _artDBContext.Entry(timesheet).State = EntityState.Modified;
        _artDBContext.SaveChanges();          
    }
}

以下是我遇到的错误信息:

未记录的错误: 响应状态为500

响应主体
下载
System.InvalidOperationException: 在尝试激活'ArchPortal.ART.WebAPI.Controllers.TimesheetController'时无法解析类型'ArchPortal.ART.Repository.Interface.ITimesheetRepository'。
   在Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
   在lambda_method34(Closure , IServiceProvider , Object[] )
   在Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
   在Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
   在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- 上一位置的堆栈跟踪的末尾 ---
   在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   在Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   在Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   在Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   在Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   在Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

头部
=======
Accept: */*
Host: localhost:7154
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
:method: POST
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: .AspNetCore.Antiforgery.hST4KUX5M6E=CfDJ8EXEmdxP_L9KuMlGxtZS0jlhrSBRZ4IrUDAEaYEvVQFB1cU3eYpFpnLe7UcI4uWnoBnl4laufEKpAfzGZxNi9FIRogfZUw748eKqm5FdObxE5qvuYse9jrb5UjVShfoanL8EajyKSdQ7sA0Hd7Kah1s,.AspNetCore.Session=CfDJ8EXEmdxP%2FL9KuMlGxtZS0jkQY5wu3raX%2BfcdeJaexR64LKlxAZEevFg2yi2OgH33rxoNy09Kip%2B8k2%2BGALHBwComubsMgU86lD%2BXqDcvH3FV4WbSHu7Kk%2FAehnMuapbWdQPT76kLHcwtcaVtMw9JdnbxFi6gtxusJ%2BVX5zoav0%2BT
Origin: https://localhost:7154
Referer: https://localhost:7154/swagger/index.html
Content-Length: 0
sec-ch-ua: "Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-site: same-origin
sec-fetch-mode: cors
sec-fetch-dest: empty

响应头
content-type: text/plain; charset=utf-8
date: Mon,09 Jan 2023 08:35:26 GMT
server: Kestrel

我正在尝试测试计算是否有效。数据已存在于数据库中。

英文:

I'm trying to perform a test using the Swagger API. Whenever I'm trying to input the timesheedid it gaves Error 500.

Here's the method

 public void ComputeProductivity(long timesheetId)
        {
            var timesheet = _artDBContext.Timesheets.FirstOrDefault(x =&gt; x.Id == timesheetId);
            if (timesheet != null)
            {
                var percentage = 100;
                var conversionValue = 60;
                var weekValue = 5;
                var totalWorkingHoursPerWeek = 7 / 365;
timesheet.TotalHoursWorked = Convert.ToDecimal(timesheet.TimesheetDateOut - timesheet.TimesheetDateIn);
                timesheet.ProductivityPerc = timesheet.TotalHoursWorked * percentage; 
                timesheet.ProductivityHr = timesheet.ProductivityMin / conversionValue;
                timesheet.ProductivityMin = timesheet.TotalHoursWorked * conversionValue;
                timesheet.FTERatio = (timesheet.TotalHoursWorked * weekValue) / (timesheet.TotalHoursWorked * totalWorkingHoursPerWeek );

                _artDBContext.Entry(timesheet).State = EntityState.Modified;
                _artDBContext.SaveChanges();          
            }
        }

and here's the error I'm getting

Undocumented
Error: response status is 500

Response body
Download
System.InvalidOperationException: Unable to resolve service for type &#39;ArchPortal.ART.Repository.Interface.ITimesheetRepository&#39; while attempting to activate &#39;ArchPortal.ART.WebAPI.Controllers.TimesheetController&#39;.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
   at lambda_method34(Closure , IServiceProvider , Object[] )
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.&lt;&gt;c__DisplayClass7_0.&lt;CreateActivator&gt;b__0(ControllerContext controllerContext)
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.&lt;&gt;c__DisplayClass6_0.&lt;CreateControllerFactory&gt;g__CreateController|0(ControllerContext controllerContext)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State&amp; next, Scope&amp; scope, Object&amp; state, Boolean&amp; isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeFilterPipelineAsync&gt;g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeAsync&gt;g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeAsync&gt;g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.&lt;Invoke&gt;g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Host: localhost:7154
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
:method: POST
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: .AspNetCore.Antiforgery.hST4KUX5M6E=CfDJ8EXEmdxP_L9KuMlGxtZS0jlhrSBRZ4IrUDAEaYEvVQFB1cU3eYpFpnLe7UcI4uWnoBnl4laufEKpAfzGZxNi9FIRogfZUw748eKqm5FdObxE5qvuYse9jrb5UjVShfoanL8EajyKSdQ7sA0Hd7Kah1s,.AspNetCore.Session=CfDJ8EXEmdxP%2FL9KuMlGxtZS0jkQY5wu3raX%2BfcdeJaexR64LKlxAZEevFg2yi2OgH33rxoNy09Kip%2B8k2%2BGALHBwComubsMgU86lD%2BXqDcvH3FV4WbSHu7Kk%2FAehnMuapbWdQPT76kLHcwtcaVtMw9JdnbxFi6gtxusJ%2BVX5zoav0%2BT
Origin: https://localhost:7154
Referer: https://localhost:7154/swagger/index.html
Content-Length: 0
sec-ch-ua: &quot;Not?A_Brand&quot;;v=&quot;8&quot;, &quot;Chromium&quot;;v=&quot;108&quot;, &quot;Google Chrome&quot;;v=&quot;108&quot;
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: &quot;Windows&quot;
sec-fetch-site: same-origin
sec-fetch-mode: cors
sec-fetch-dest: empty

Response headers
content-type: text/plain; charset=utf-8
date: Mon,09 Jan 2023 08:35:26 GMT
server: Kestrel

I'm trying to test if the computation works. And the data exist already in the database.

答案1

得分: 0

您的问题意味着您的 ITimesheetRepository 接口未在您的 DI(依赖注入)容器中注册,因此在构建控制器时找不到它。

要解决此问题,假设您正在使用默认的 ASP.NET Core DI(根据错误消息似乎是这样),并假设您的实现类名为 TimesheetRepository,您需要根据 ASP.NET Core 版本在您的 Program.csStartup.cs 中添加以下一行代码:

// 假设您在同一文件中的某处有以下行:
var builder = WebApplication.CreateBuilder(args); 
...
// 要插入的行
builder.Services.AddScoped<ITimesheetRepository, TimesheetRepository>();
...
// 并且您应该在插入的行之后拥有以下行:
var app = builder.Build();
...
app.Run();

另请参阅:MSDN:ASP.NET Core 中的依赖注入

英文:

Your issue means that your ITimesheetRepository interface is not registered in your DI container, so it can't be found when you're constructing your Controller.

To fix this, assuming you're using the default ASP.NET Core DI (as it seems from the error message) and assuming that your implementation class is called TimesheetRepository, you need to add one line to either your Program.cs or Startup.cs depending on the ASP.NET Core version:

// I assume you have the following line somewhere in the same file:
var builder = WebApplication.CreateBuilder(args); 
...
// Line to insert
builder.Services.AddScoped&lt;ITimesheetRepository, TimesheetRepository&gt;();
...
// and you should have the following lines _below_ the inserted one:
var app = builder.Build();
...
app.Run();

See also: MSDN: Dependency injection in ASP.NET Core

huangapple
  • 本文由 发表于 2023年1月9日 16:20:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054659.html
匿名

发表评论

匿名网友

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

确定