Skip to content

Instantly share code, notes, and snippets.

Last active December 29, 2022 20:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?

Creating a ASP.NET Core Web API from scratch

Requires .NET 7 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

cd MyApi

dotnet add package Microsoft.Extensions.DependencyInjection
dotnet add package DotNetEnv
dotnet add package MySql.Data
dotnet add package sqlkata
dotnet add package SqlKata.Execution

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(

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