【问题标题】:Unit Of Work with Dependency Injection Controller Error [closed]依赖注入控制器错误的工作单元[关闭]
【发布时间】:2020-05-20 10:55:47
【问题描述】:

您好,我目前正在使用 MVC 开发 WebAPI。 发出 Get-Request(通过 Swagger)时会引发以下错误:

System.InvalidOperationException: Unable to resolve service for type 'Wettkampf_API_Semesterprojekt.Models.Repository.IRepository`1[Wettkampf_API_Semesterprojekt.Models.WettkampfContext]' while attempting to activate 'Wettkampf_API_Semesterprojekt.Controllers.VereinController'.

   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)

   at lambda_method(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 where exception was thrown ---

   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 where exception was thrown ---

   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)

   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)

   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)

   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)



HEADERS

=======

Accept: text/plain

Accept-Encoding: gzip, deflate, br

Accept-Language: de,en-US;q=0.7,en;q=0.3

Connection: close

Cookie: Webstorm-127f7717=d590bea8-03f2-4cbb-9abb-c1d363fc6bad

Host: localhost:44325

Referer: https://localhost:44325/swagger/index.html

Te: trailers

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0

控制器

namespace Wettkampf_API_Semesterprojekt.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class VereinController : ControllerBase
    {
        //Controller: Verein, PunkteKampf, GastHeim, RingerWiegeliste, Wettkampfabend, Bundesliga
        private readonly IRepository<WettkampfContext> _repository;
        private readonly IUnitOfWork _unitOfWork;
        public VereinController(IRepository<WettkampfContext> repository, IUnitOfWork uw)
        {
            _repository = repository;
            _unitOfWork = uw;
        }

        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<ActionResult<IEnumerable<Verein>>> GetAsync()
        {
            IEnumerable<Verein> result = await _unitOfWork.Vereine.ReadAllAsync();
            if (!result.Any())
            {
                return NotFound("There is no result for your request unfortunately. Maybe add something to the database");
            }
            return Ok(result);
        }
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<ActionResult> PostAsync([FromBody] Verein v)
        {
            if (v == null)
            {
                return BadRequest("No Input Found!");
            }
            await _unitOfWork.Vereine.AddAsync(v);
            await _unitOfWork.CompleteAsync();
            return Ok(v.Name);
        }
    }
}

启动

namespace Wettkampf_API_Semesterprojekt
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<WettkampfContext>(opts => opts.UseMySql(Configuration.GetConnectionString("Wettkampf")).UseLazyLoadingProxies());
            services.AddControllers();
            services.AddMvc();
            services.AddSwaggerGen(c => c.SwaggerDoc(name: "v1", new OpenApiInfo { Title = "Bundesliga API", Version = "v1" }));
            services.AddScoped<IUnitOfWork, UnitOfWork>();
        }

        // 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.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseSwagger();

            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Bundesliga API V1"); });

        }
    }
}

工作单元类

namespace Wettkampf_API_Semesterprojekt.Models
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly DbContext _context;

        public UnitOfWork()
        {
            this._context = new WettkampfContext();
            Vereine = new VereinRepository(_context);
        }
        public IVereinRepository Vereine { get; set; }

        public async Task CompleteAsync()
        {
            await _context.SaveChangesAsync();
        }

        public async ValueTask DisposeAsync()
        {
            await _context.DisposeAsync();
        }
    }
}

所有使用和接口都正确实现。 似乎控制器没有正确注入。我知道这并不多,但我们将不胜感激。提前致谢。 ~最大

【问题讨论】:

  • 愿意向我们展示您的代码/配置吗?
  • @JayJordan - 创建实例时抛出异常,因此无法在控制器内部的某处设置断点。
  • 删除了之前的评论,因为我的问题的答案有些明显。检查下面的答案。

标签: c# asp.net-mvc asp.net-core unit-of-work


【解决方案1】:

我们来看看异常:

System.InvalidOperationException:尝试激活“Wettkampf_API_Semesterprojekt.Controllers.VereinController”时,无法解析类型“Wettkampf_API_Semesterprojekt.Models.Repository.IRepository`1[Wettkampf_API_Semesterprojekt.Models.WettkampfContext]”的服务。

因此,它无法创建VereinController 的实例,因为它需要IRepository&lt;WettkampfContext&gt;,但没有为IRepository&lt;WettkompfContext&gt; 注册服务。

您只能注入可用的服务。通常在 Startup.cs 中添加

如果我们查看您的 Startup.cs ConfigureServices() 方法,我看不到任何为 IRepository 添加服务的内容。您必须在此处添加它。

【讨论】:

  • 不幸的是它抛出了一个错误
  • 您尝试了什么,遇到了什么错误?
【解决方案2】:
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<WettkampfContext>(opts => opts.UseMySql(Configuration.GetConnectionString("Wettkampf")).UseLazyLoadingProxies());
        services.AddControllers();
        services.AddMvc();
        services.AddSwaggerGen(c => c.SwaggerDoc(name: "v1", new OpenApiInfo { Title = "Bundesliga API", Version = "v1" }));
        services.AddScoped<IUnitOfWork, UnitOfWork>();
        // Register IRepository
        services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多