简体   繁体   中英

System Aggregate Exception using .Net

I am working on an mvc .net application. When I run dotnet build the solution is built normally with no errors. However, when I run the solution to display the api using swagger, it throws a system aggregated exception and the run fails. The exception is being thrown at a certain part in my Program.cs file. The Program.cs file looks something like this:

using Example.Api.Data;
using Example.Services;
using Example.Services.Interfaces;
using Example.Core;
using Example.Core.Interfaces;
using Example.Core.Repositories;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerUI;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddAutoMapper(typeof(StartupBase));
builder.Services.AddControllersWithViews();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddTransient<IApplicantService, ApplicantService>();
builder.Services.AddTransient<IApplicantSurveyChoicesService, ApplicantSurveyChoicesService>();
builder.Services.AddTransient<IApplicantSurveyService, ApplicantSurveyService>();
builder.Services.AddTransient<IChoiceService,ChoiceService>();
//I basically did add transient for everyone of my services 
builder.Services.AddSwaggerGen();
var app = builder.Build(); //this is where the exception is being thrown

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
    /*app.UseSwagger();
    app.UseSwaggerUI();*/
}
else
{
    app.UseExceptionHandler("/Home/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.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
        options.RoutePrefix = string.Empty;
    });

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();

app.Run(); 

It throws the following exception: 'System.AggregateException' in Microsoft.Extensions.DependencyInjection.dll Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Example.Services.Interfaces.IApplicantService Lifetime: Transient ImplementationType: Example.Services.ApplicantService': Unable to resolve service for type 'Example.Core.Interfaces.IUnitOfWork' while attempting to activate 'Example.Services.ApplicantService'.) and the error appears for every single time I call AddTransient I am fairly new to the dotnet framework and I am still a beginner and would appreciate your help!

The IUnitOfWork file consists of the following:

    public interface IUnitOfWork : IDisposable
    {
        IApplicantRepository Applicants { get; }

        IApplicantSurveyChoicesRepository ApplicantSurveyChoices { get; }

        IApplicantSurveyRepository ApplicantSurveys { get; }

        IChoiceRepository Choices{ get; }

        Task<int> CommitAsync();
    }

The UnitOfWork class is just an implementation of the interface as such:

  public UnitOfWork(DbContext context)
        {
            this._context = context;
        }
        public UnitOfWork(DbContext context, DbContext context1, IHostingEnvironment _environment, IHttpContextAccessor httpContextAccessor)
        {
            this._context = context;
            this._environment = _environment;
            _httpContextAccessor = httpContextAccessor;
        }

        public IApplicantRepository Applicants => _applicantRepository = _applicantRepository ?? new ApplicantRepository(_context, Config, _httpContextAccessor);

        public IApplicantSurveyChoicesRepository ApplicantSurveyChoices => _applicantsurveychoicesrepository = _applicantsurveychoicesrepository ?? new ApplicantSurveyChoicesRepository(_context, Config, _httpContextAccessor);

        public IApplicantSurveyRepository ApplicantSurveys => _applicantsurveysrepository  = _applicantsurveysrepository ?? new ApplicantSurveyRepository(_context, Config, _httpContextAccessor);

        public IChoiceRepository Choices => _choicerepository = _choicerepository ?? new ChoiceRepository(_context, Config, _httpContextAccessor);
        public async Task<int> CommitAsync()
        {
            return await _context.SaveChangesAsync();
        }

        public void Dispose()
        {
            _context.Dispose();
        }

I believe swagger is running through your controller endpoints and will activate some services while some services remain just registered but not resolved. So in my theory the error will also happen when you use the logic of the ApplicantService.

The error says it can't resolve the implementation of IUnitOfWork while trying to activate ApplicantService. So I would guess, you have missed a registration from the class UnitOfWork, or the interface referenced in the class UnitOfWork. But that would be the place where I would look.

Singelton, Scope and Transient should not have any relevance at this stage.

I figured out the issue. One of my controllers was not properly routed which led to the exception being thrown! Thank you everyone for your help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM