Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

269
Vistas
How import WebApplicationBuilder in a Class Library?

I want to create an extension method for WebApplicationBuilder:

public static void AddData(this WebApplicationBuilder builder)
{
    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
    builder.Services.AddDbContext<ApplicationDbContext>(option =>
    {
        option.UseSqlite(connectionString);
    });
}

this method works in a project that use: <Project Sdk="Microsoft.NET.Sdk.Web">, but if I put this method in a class libary then it doesn't work (<Project Sdk="Microsoft.NET.Sdk>) because it doesn't find Microsoft.AspNetCore.Builder

Otherwise, if I use <Project Sdk="Microsoft.NET.Sdk.Web"> the compiler say that there is no Main in the project.

How can I do?

Why can't I write this?

using Microsoft.AspNetCore.Builder;
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I did this recently when I converted to a .Net 6 project. I wasn't able to extend the Builder either, so I added the extension to the IServiceCollection and passed in the configuration. So to use your example, my code looked more like:

public static void AddData(this IServiceCollection services, ApplicationSettings appSettings)
{
    services.AddDbContext<ApplicationDbContext>(option =>
    {
        option.UseSqlite(appSettings.ConnectionString);
    });
}

Where ApplicationSettings is a custom class that is bound to the app settings in the json. So my Program.cs has these lines:

var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;

var appSettings = new ApplicationSettings();
configuration.Bind(appSettings);
builder.Services.AddData(appSettings);

Using the IServiceCollection in the extension method only requires:

using Microsoft.Extensions.DependencyInjection;
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda