Skip to content

Latest commit

 

History

History
65 lines (47 loc) · 2.33 KB

File metadata and controls

65 lines (47 loc) · 2.33 KB

Web API

CSharp

This example demonstrates the creation of a Web API application in the pure DI paradigm using the Pure.DI code generator.

The composition setup file is Composition.cs:

using Pure.DI;
using Pure.DI.MS;
using static Pure.DI.Lifetime;

namespace WebAPI;

partial class Composition : ServiceProviderFactory<Composition>
{
    private void Setup() => DI.Setup()
        .Roots<ControllerBase>()

        .Bind().As(Singleton).To<ClockViewModel>()
        .Bind().To<ClockModel>()
        .Bind().As(Singleton).To<Ticks>()

        // Infrastructure
        .Bind().To<MicrosoftLoggerAdapter<TT>>()
        .Bind().To<CurrentThreadDispatcher>();
}

The composition class inherits from ServiceProviderFactory<T>, where T is the composition class itself.

The web application entry point is in the Program.cs file:

var builder = WebApplication.CreateBuilder(args);

using var composition = new Composition();

// Uses Composition as an alternative IServiceProviderFactory
builder.Host.UseServiceProviderFactory(composition);

The project file looks like this:

<Project Sdk="Microsoft.NET.Sdk.Web">
    ...
    <ItemGroup>
        <PackageReference Include="Pure.DI" Version="2.3.6">
            <PrivateAssets>all</PrivateAssets>
            <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
        <PackageReference Include="Pure.DI.MS" Version="2.3.6" />
    </ItemGroup>

</Project>

It contains additional references to NuGet packages:

Pure.DI NuGet DI source code generator
Pure.DI.MS NuGet Add-ons for Pure.DI to work with Microsoft DI