2

espero me puedan ayudar, tengo un problema al inyectar el context de una bd. El context y entidades están en un paquete .nupkg independiente del proyecto, entonces los métodos del context son estos:

public DbVContext()
        {
        }

public DbVContext(DbContextOptions<DbVContext> options)
    : base(options)
{
}

public DbVContext(string instancia = "db_v", string host = "localhost", string user = "username", string password = "password")
{
    _host = host;
    SetDataConnection(instancia, user, password);
}

private void SetDataConnection(string instancia, string user, string password)
{
    Connection = $"Server={_host}; Database={instancia}; User ID={user}; Password={password}";
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer(Connection).EnableSensitiveDataLogging().EnableDetailedErrors();
    }
}

y así lo inyecto en el startup.

services.AddDbContext<DbVContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServer")));

el error que recibo al ejecutar el api es el siguiente y pues ya no se ejecuta nada, nose porque marca error con el constructor de strings, ademas de que este error sale dos veces en la consola:

System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: CONTEXTV.DbVContext Lifetime: Scoped ImplementationType: CONTEXTV.DbVContext ': Unable to activate type 'CONTEXTV.DbVContext'. The following constructors are ambiguous:
Void .ctor(System.String, System.String, System.String, System.String)
Void .ctor(Microsoft.EntityFrameworkCore.DbContextOptions`1[CONTEXTV.DbVContext]))
 ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: CONTEXTV.DbVContext Lifetime: Scoped Im
plementationType: CONTEXTV.DbVContext': Unable to activate type 'CONTEXTV.DbVContext'. The following constructors are ambiguous:
Void .ctor(System.String, System.String, System.String, System.String)
Void .ctor(Microsoft.EntityFrameworkCore.DbContextOptions`1[CONTEXTV.DbVContext])
 ---> System.InvalidOperationException: Unable to activate type 'CONTEXTV.DbVContext'. The following constructors are ambiguous:
Void .ctor(System.String, System.String, System.String, System.String)
Void .ctor(Microsoft.EntityFrameworkCore.DbContextOptions`1[CONTEXTV.DbVContext])
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implemen
tationType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain ca
llSiteChain, Int32 slot)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor serviceDescriptor, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.ValidateService(ServiceDescriptor descriptor)
   --- End of inner exception stack trace ---
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.ValidateService(ServiceDescriptor descriptor)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, ServiceProviderOptions options)
   --- End of inner exception stack trace ---
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProvider
Options options)
   at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
   at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()

Gracias

12
  • Que es lo que tratas de hacer con ese tercer constructor y ese método SetDataConnection() ? el 25 oct. 2021 a las 18:04
  • (Error while validating the service descriptor 'ServiceType: CONTEXTV.DbVContext Lifetime: Scoped ImplementationType: CONTEXTV.DbVContext ': Unable to activate type 'CONTEXTV.DbVContext'. The following constructors are ambiguous:... Yup. Repara tus constructores.
    – Arriel
    el 25 oct. 2021 a las 18:21
  • 1
    @Arthur al setear el servicio ya le estas pasando la cadena de conexion que esta en appSettings.json probablemente, no necesitas construir vos manualmente la cadena de conexion
    – Cmbuffa
    el 25 oct. 2021 a las 19:10
  • 1
    no necesitas el constructor que recibe 4 strings..
    – Cmbuffa
    el 25 oct. 2021 a las 19:14
  • 1
    Bueno, lo que pides no es descabellado. A veces es necesario obtener esas cadenas de conexión de manera dinámica. Este post habla exactamente de lo que deseas hacer. Aquí hay otro. Suerte
    – Arriel
    el 26 oct. 2021 a las 12:01

1 respuesta 1

0

tu conexion viene de appsetting.json, ya no es necesario agregar SetDataConnection,

intenta de esta manera

public class DbVContext: DbContext
{

  public DbVContext(DbContextOptions<DbVContext> options) : base(options) { }
  protected override void OnModelCreating(ModelBuilder builder)
  {
      base.OnModelCreating(builder);
  }

}

//appsettings.json
{
  "ConnectionStrings": {
    "SqlServer": "tu cadena de conexion"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}


//agregas tu servicio
services.AddDbContext<DbVContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServer")));

  

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.