Skip to content

Instantly share code, notes, and snippets.

@odan
Last active March 7, 2024 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odan/f778c46b64f3cc81bdcbdd870c31c77a to your computer and use it in GitHub Desktop.
Save odan/f778c46b64f3cc81bdcbdd870c31c77a to your computer and use it in GitHub Desktop.

Creating a ASP.NET Core Web API from scratch

Requires .NET 8 SDK

dotnet new sln -o MyApi
cd MyApi

dotnet new webapi -o MyApi

dotnet sln add ./MyApi/MyApi.csproj

dotnet new xunit -o MyApi.Tests

dotnet sln add ./MyApi.Tests/MyApi.Tests.csproj

dotnet add ./MyApi.Tests/MyApi.Tests.csproj reference ./MyApi/MyApi.csproj

rem Add database project for MS-SQL projects
rem https://github.com/microsoft/dacfx
rem SQL Server Data Tools (SSDT) must be installed!
rem https://visualstudio.microsoft.com/en/vs/features/ssdt/

dotnet new install "Microsoft.Build.Sql.Templates"
dotnet new sqlproj -o Database
dotnet sln add ./Database/Database.sqlproj

rem Add git and editor files to project root
dotnet new editorconfig
dotnet new gitignore

rem Add packages to the main project
cd MyApi

dotnet add package DotNetEnv
rem dotnet add package MySql.Data
dotnet add package System.Data.SqlClient
dotnet add package sqlkata
dotnet add package SqlKata.Execution

rem Optional

rem Swagger
dotnet add package Swashbuckle.AspNetCore

Read more

Replacing an already registered dependency for testing purposes

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
// ...

builder.ConfigureServices((hostBuilderContext, services) =>
{
    // Replacing an already registered dependency
    services.Replace(ServiceDescriptor.Transient<IFoo, Foo>());

    // Another syntax 
    services.Replace(ServiceDescriptor.Transient<IFoo>(_ => new Foo()));

    // Using a factory function for custom logic
    services.Replace(ServiceDescriptor.Transient<IFoo>((container) =>
    {
        // Custom logic
        // ...

        // var bar = container.GetRequiredService<Bar>();

        return new Foo();
    }));

    // Using a ServiceDescriptor
    var descriptor = new ServiceDescriptor(
            typeof(IFoo),
            typeof(Foo),
            ServiceLifetime.Transient);
    services.Replace(descriptor);
});

Note, this might not work with static class methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment