Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How import WebApplicationBuilder in a Class Library?

Tags:

c#

.net

asp.net

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;
like image 983
Valerio Ceccarelli Avatar asked Aug 30 '25 16:08

Valerio Ceccarelli


2 Answers

I had exactly the same problem but this Microsoft doc explains what you need to do.

Add

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>

to your .csproj and you can then use

using Microsoft.AspNetCore.Builder;

in your regular class library which targets Microsoft.NET.Sdk.

like image 92
Dutts Avatar answered Sep 02 '25 17:09

Dutts


For future people coming here. You can use IHostApplicationBuilder from Microsoft.Extensions.Hosting.Abstractions

like image 24
phastari Avatar answered Sep 02 '25 16:09

phastari