GrpcService.md

June 18, 2026 ยท View on GitHub

gRPC service

CSharp

This example shows how to build a gRPC service with Pure.DI and ASP.NET Core hosting. The generated composition exposes the service and application dependencies through the Microsoft service-provider pipeline.

Tip

The gRPC service type itself is a composition root. Keep the ASP.NET Core gRPC registration (AddGrpc) in Program.cs, and let Pure.DI create the service graph.

The composition setup file is Composition.cs:

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

namespace GrpcService;

partial class Composition : ServiceProviderFactory<Composition>
{
    // IMPORTANT:
    // Only composition roots (regular or anonymous) can be resolved through the `IServiceProvider` interface.
    // These roots must be registered using `Root<>(...)` or `RootBind<>()` calls.
    [System.Diagnostics.Conditional("DI")]
    private static void Setup() => DI.Setup()
        .Root<ClockService>()

        .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. Only registered roots can be resolved through the Microsoft IServiceProvider, so the gRPC service type is declared as a root.

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

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc();

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.4.3">
            <PrivateAssets>all</PrivateAssets>
            <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
        <PackageReference Include="Pure.DI.MS" Version="2.4.3" />
    </ItemGroup>

</Project>

It contains additional references to NuGet packages:

Pure.DINuGetDI source code generator
Pure.DI.MSNuGetAdd-ons for Pure.DI to work with Microsoft DI