0

Using .NET 6 and Visual Studio 2022 Current, and I'm getting the error when I try to test the API in Swagger. Unable to resolve service for type while attempting to activate. also, get the error when I ad the service like add all like the builder.Services.AddSingleton<IDataAcess,DataAcess>();

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: WebApi.Utilities.IDataAcess Lifetime: Singleton ImplementationType: WebApi.Utilities.DataAcess': Unable to resolve service for type 'WebApi.Utilities.DBAccess' while attempting to activate 'WebApi.Utilities.DataAcess'.)'

When I run the app, I get the error as in the image.

enter image description here

I'm so sure what the issue is, but whenever I try adding the services in .Net 5 or below, it works perfectly fine.

Controler

    using Microsoft.AspNetCore.Mvc;
    using WebApi.Models;
    using WebApi.Utilities;
    
    namespace WebApi.Controllers
    {
        [ApiController]
        [Route("analysis")]
        public class analysisDataController : ControllerBase
        {
            private IDataAcess _dataAcess;
            public analysisDataController(IDataAcess dataAcess)
            {
                _dataAcess = dataAcess;
            }
    
            [HttpGet]
            public ActionResult<IEnumerable<Clients>> getAllClients()
            {
                return _dataAcess.getClients().ToList();
            }
        }
    }

Model

    using System.ComponentModel.DataAnnotations;
    
    namespace WebApi.Models
    {
        public class Clients
        {
            [Required]
            public Guid id { get; set; }
            [Required]
            public string usercode { get; set; }
            [Required]
            public int clientid { get; set; }
            [Required]
            public string clientName { get; set; }
            [Required]
            public int searchId { get; set; }
            [Required]
            public string searchName { get; set; }
        }
    }

Data Access

    using WebApi.Models;
    
    namespace WebApi.Utilities
    {
        public class DataAcess : IDataAcess
        {
            IDBAccess _dbAccess;
            public DataAcess(DBAccess dBAccess)
            {
                _dbAccess = dBAccess;
            }
    
            public List<Clients> getClient(string user)
            {
                string query = @"SELECT u.UserID AS USER, uc.clientID AS clientID, cl.Name AS clientName,search.ID AS searchID, search.Description AS searchName 
                                     FROM testdb1.user_client AS uc
                                    JOIN testdb2.client AS cl ON uc.clientID = cl.ID
                                    JOIN testdb1.user AS u ON u.ID = uc.userID
                                     JOIN testdb2.set ON set.IDClient = uc.clientID
                                    JOIN testdb2.search ON search.IDSet = set.ID
                                     WHERE u.UserID = '" + user + "'";
                if (!string.IsNullOrEmpty(user))
                {
                    var clientData = _dbAccess.RunQuery<Clients>(query);
    
                    return clientData.ToList();
                }
                else
                {
                    return null;
                }
            }
    
            public IEnumerable<Clients> getClients()
            {
                string query = @"SELECT u.UserID AS USER, uc.clientID AS clientID, cl.Name AS clientName,search.ID AS searchID, search.Description AS searchName 
                                     FROM testedb1.user_client AS uc
                                    JOIN testdb1.client AS cl ON uc.clientID = cl.ID
                                    JOIN testdb1.user AS u ON u.ID = uc.userID
                                     JOIN testdb2.set ON set.IDClient = uc.clientID
                                    JOIN testdb2.search ON search.IDSet = set.ID";
    
                var clients = _dbAccess.RunQuery<Clients>(query);
                if(clients.Count != 0)
                    return clients;
    
                return null;
            }
        }
    }


DBAccess Class

    using Dapper;
    using MySql.Data.MySqlClient;
    
    namespace WebApi.Utilities
    {
        public class DBAccess : IDBAccess
        {
            ILogger _logger;
    
            public DBAccess(ILogger logger)
            {
                _logger = logger;
            }
            public List<T> RunQuery<T>(string query)
            {
                try
                {
                    const string conStr = @"server='####';userid='Aubz';password='Test';database='testdb1.clients'";
                    using (MySqlConnection conn = new MySqlConnection(conStr))
                    {
                        return conn.Query<T>(query).ToList();
                    }
                }
                catch (Exception e)
                {
                    _logger.log(e.Message);
                    throw e;
                }
    
            }
        }
    }

Logger Class

        namespace WebApi.Utilities
        {
        public class Logger : ILogger
        {
            public void log(string logData)
            {
                Console.WriteLine(logData);
            }
        }
    }

Interface class IDataAcess

    using WebApi.Models;
    
    namespace WebApi.Utilities
    {
        public interface IDataAcess
        {
            List<Clients> getClient(string user);
            IEnumerable<Clients> getClients();
        }
    }

Interface IDBAccess

    namespace WebApi.Utilities
    {
        public interface IDBAccess
        {
            List<T> RunQuery<T>(string query);
        }
    }

Interface Ilogger

    namespace WebApi.Utilities
    {
        public interface ILogger
        {
            void log(string logData);
        }
    }

Program.cs

    using WebApi.Utilities;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    
    builder.Services.AddControllers();
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    
    app.UseHttpsRedirection();
    
    app.UseAuthorization();
    
    app.MapControllers();
    
  app.Run();
3
  • 2
    This is not a VS 2022 issue, or even any visual studio issue, you have simply not registered the service. Possible something like builder.Services.AddSingleton<IDataAcess,DataAcess>(). Though you really should look up how to use Dependency injection Commented Nov 22, 2021 at 6:53
  • I did add the builder.Services.AddSingleton<IDataAcess,DataAcess>(); at the begining like we use it in .NET 5 but I get the error below: System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: WebApi.Utilities.IDataAcess Lifetime: Singleton ImplementationType: WebApi.Utilities.DataAcess': Unable to resolve service for type 'WebApi.Utilities.DBAccess' while attempting to activate 'WebApi.Utilities.DataAcess'.)' Commented Nov 22, 2021 at 12:32
  • According to the error, it's not DataAcess you need to register, but DBAccess Commented Nov 24, 2021 at 7:35

1 Answer 1

1

The problem is you don't configure the Dependency injection Container

  1. Your controller depend on IDataAcess but you don't provide any concrete implementation for it, Add the DataAcess as concert implementation in program.cs
builder.Services.AddSingleton<IDataAcess,DataAcess>();
  1. DataAcess is depended on the concrete DBAccess and store it as IDBAccess, this is pointless your class should depend on Interface not on concrete
IDBAccess _dbAccess;
public DataAcess(IDBAccess dBAccess)  //<<< change to be depend on interface IDBAccess 
{
    _dbAccess = dBAccess;
}
  1. Provide a concrete implementation to IDBAccess in program.cs
builder.Services.AddSingleton<IDBAccess ,DBAccess>();

Finally, your program.cs will be look like this

using WebApi.Utilities;
    
var builder = WebApplication.CreateBuilder(args);
    
// Add services to the container.
builder.Services.AddSingleton<IDBAccess ,DBAccess>();   //<<<< adding IDBAccess
builder.Services.AddSingleton<IDataAcess,DataAcess>();  //<<<<< adding IDataAcess
    
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); 
builder.Services.AddSwaggerGen();
    
var app = builder.Build();  
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
   app.UseSwagger();
   app.UseSwaggerUI();
}  
app.UseHttpsRedirection();   
app.UseAuthorization();   
app.MapControllers();
app.Run();
Sign up to request clarification or add additional context in comments.

5 Comments

thanks for getting back to me I did add the builder.Services.AddSingleton<IDataAcess,DataAcess>(): but the error. System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: WebApi.Utilities.IDataAcess Lifetime: Singleton ImplementationType: WebApi.Utilities.DataAccess: Unable to resolve service for type 'WebApi.Utilities.DBAccess' while attempting to activate 'WebApi.Utilities.DataAcess'.)'
This error message say that you did not add IDBAccess in the step 2 ...please read the answer and be sure from the step 2 ... Did you change DataAcess constructor to take IDBAccess not DBAccess ?
Thanks for getting back to me. Are you referring to this part? if yes please could you elaborate a bit further. public DataAcess(DBAccess dBAccess) { _dbAccess = dBAccess; }
Yes I mean this, you should change it to public DataAcess(IDBAccess dBAccess) { _dbAccess = dBAccess; } you should use the interface IDBAccess not a concrete DBAccess and make sure that you add it in dependency container builder.Services.AddSingleton<IDBAccess ,DBAccess>(); in your program.cs
Thanks, I got it it's working now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.