FunctionInjection 0.1.0-preview.1

This is a prerelease version of FunctionInjection.
dotnet add package FunctionInjection --version 0.1.0-preview.1
                    
NuGet\Install-Package FunctionInjection -Version 0.1.0-preview.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="FunctionInjection" Version="0.1.0-preview.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="FunctionInjection" Version="0.1.0-preview.1" />
                    
Directory.Packages.props
<PackageReference Include="FunctionInjection" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add FunctionInjection --version 0.1.0-preview.1
                    
#r "nuget: FunctionInjection, 0.1.0-preview.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package FunctionInjection@0.1.0-preview.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=FunctionInjection&version=0.1.0-preview.1&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=FunctionInjection&version=0.1.0-preview.1&prerelease
                    
Install as a Cake Tool

Function Injection

NuGet ci

Every operation of an application as a function: a delegate type, made by a factory that takes its dependencies, registered as a service. Whoever needs the operation asks for the delegate.

public delegate Task<Order?> GetOrderById(Guid id, CancellationToken cancellationToken);

public static class OrderFunctions
{
    [Function]
    public static GetOrderById GetOrderById(IOrderRepository orders) => orders.GetAsync;
}

builder.Services.AddFunctions();

app.MapGet("/orders/{id}", (Guid id, GetOrderById getOrderById, CancellationToken cancellationToken) => getOrderById(id, cancellationToken));
  • Registration. [Function] on the factory and a source generator writes the registration, or AddFunction by hand.
  • Catalog. Name, description, tags, lifetime and dependencies of every function, in IFunctionCatalog.
  • Decorators. Around one function with Decorate, or around many at once with AddFunctionDecorator; tracing and metrics come with the library.
  • Tools. The functions of the catalog as tools for a chat client of Microsoft.Extensions.AI and for an MCP server.
  • Tests and startup. ReplaceFunction puts a fake in place of a function; ValidateFunctions creates them all once.
  • Speed. A call is a call of a delegate: as fast as an interface, 19 to 28 times faster than a mediator (benchmarks).

Everything is in the FunctionInjection namespace, one using for the attributes, the registration and the decorators; the tools are in FunctionInjection.AI and FunctionInjection.Mcp.

Install

dotnet add package FunctionInjection --prerelease

The package holds the library, for .NET 10 and .NET 11, and the source generator: [Function] works as soon as it is installed. FunctionInjection.AI and FunctionInjection.Mcp add the tools for a chat client and for an MCP server.

Coming from MediatR

The same shape of code, without the dispatch in the middle: the endpoint asks for the operation itself, and the compiler sees what it takes and what it gives.

MediatR Function Injection
record GetOrder(Guid Id) : IRequest<Order?> delegate Task<Order?> GetOrderById(Guid id, CancellationToken cancellationToken)
class GetOrderHandler : IRequestHandler<GetOrder, Order?> [Function] static GetOrderById GetOrderById(IOrderRepository orders)
services.AddMediatR(c => c.RegisterServicesFromAssembly(...)) services.AddFunctions(), written by the source generator
await sender.Send(new GetOrder(id), cancellationToken) await getOrderById(id, cancellationToken)
IPipelineBehavior<TRequest, TResponse> FunctionDecorator, with AddFunctionDecorator
A missing handler fails at run time A factory that cannot be registered fails the build (FI001-FI009)
  • What it does not do. There are no notifications with many handlers and no dispatch from a request type known only at run time: an operation has one implementation, and whoever calls it names its type. A stream is a function that returns an IAsyncEnumerable<T>.
  • Moving step by step. A handler becomes a function by turning its Handle method into the lambda a factory returns, with the handler's constructor parameters as the factory's; the two libraries can live in the same application while the move goes on.
  • Speed. A call costs what a call of a delegate costs. In the benchmarks a function takes 2.6 ns, as a service called through its interface, where MediatR takes 70 ns and Mediator 49; with a behaviour in front, 22 ns against 103 and 74. In a whole request, with the scope and the resolution, it is 1.2 times the interface, against 1.4 and 1.7.

Registration with the source generator

The generator writes one registration for each factory marked with [Function]: the delegate type is the one the method returns, the dependencies are its parameters, as many as it has. AddFunctions is generated in the root namespace of the project, internal, and registers every marked factory of that project, once however many times it is called.

[Function(Lifetime = ServiceLifetime.Singleton)]
public static GetToday GetToday(TimeProvider clock) => () => DateOnly.FromDateTime(clock.GetLocalNow().Date);

// A generic factory names the types to register it with, once for each attribute.
[Function(typeof(Order))]
[Function(typeof(Invoice))]
public static Archive<T> Archive<T>(IStore store) where T : IDocument => ...

The package brings the generator with the library. A project that uses the sources instead, for example from a git submodule (git submodule add https://github.com/KevinValmo/function-injection), references both:

<ProjectReference Include="..\function-injection\src\FunctionInjection\FunctionInjection.csproj" />
<ProjectReference Include="..\function-injection\src\FunctionInjection.Generators\FunctionInjection.Generators.csproj"
                  OutputItemType="Analyzer" ReferenceOutputAssembly="false" />

From another project

In a solution with many projects the functions often live in one and the host in another, which cannot see an internal AddFunctions. The project then declares its registration as a static partial method marked with [FunctionRegistrations], with the name and the accessibility it wants, and the generator writes the body instead of AddFunctions:

// Shop.Ordering, the project with the functions.
public static partial class OrderingServices
{
    public static IServiceCollection AddOrdering(this IServiceCollection services) => services
        .AddScoped<IOrderRepository, OrderRepository>()
        .AddOrderingFunctions();

    [FunctionRegistrations]
    private static partial IServiceCollection AddOrderingFunctions(this IServiceCollection services);
}

// Shop.Api, the host.
builder.Services.AddOrdering();
  • The method takes an IServiceCollection and returns it, or nothing, in a class that is not generic or nested; one for each project.
  • It reaches the factories and the delegates that are internal to its project: only the method needs to be visible to the others.
  • A registration runs once for each project, however many times it is called: two projects that both need a third one can both call its method.

Diagnostics

What registration by hand leaves to run time, the generator reports when compiling:

Id Error
FI001 The factory is not static
FI002 The factory does not return a delegate
FI003 The factory, or a type that contains it, is private or generic
FI004 A parameter is passed by reference
FI005 A generic factory without its type arguments, or with the wrong number of them
FI006 Two factories return the same delegate type
FI007 Two functions have the same name
FI008 A method marked with [FunctionRegistrations] is not a static partial method that takes an IServiceCollection
FI009 Two methods of the same project are marked with [FunctionRegistrations]

Registration by hand

AddFunction takes the dependency types and the delegate type, then the factory: a static method, an instance method or a lambda. The typed overloads go from zero to seven dependencies; a factory with more takes the IServiceProvider and resolves them itself. The two ways live together: a function that needs Decorate or the fluent settings is registered by hand, without [Function].

builder.Services.AddFunction<IOrderRepository, GetOrderById>(OrderFunctions.GetOrderById)
    .WithName("orders.get-by-id")
    .WithDescription("Gets an order by ID.")
    .WithTags("orders", "read");

builder.Services.AddFunction<TimeProvider, GetToday>(clock => () => DateOnly.FromDateTime(clock.GetLocalNow().Date))
    .WithLifetime(ServiceLifetime.Singleton);

builder.Services.AddFunction<PlaceOrder>(provider => OrderFunctions.PlaceOrder(
    provider.GetRequiredService<IOrderRepository>(),
    provider.GetRequiredService<ITransactionRunner>()));

Metadata and catalog

[FunctionMetadata] on the delegate gives the name, the description and the tags; the fluent settings of a function registered by hand override them. Without a name, the delegate type name is used; a generic delegate is named with its type arguments, such as Func<Int32, String>. Tags are trimmed and deduplicated ignoring case, and an empty tag is rejected.

[FunctionMetadata(Name = "orders.get-by-id", Description = "Gets an order by ID.", Tags = ["orders", "read"])]
public delegate Task<Order?> GetOrderById(Guid id, CancellationToken cancellationToken);

foreach (var function in app.Services.GetRequiredService<IFunctionCatalog>().Functions)
{
    Console.WriteLine($"{function.Name} ({function.Lifetime}) <- {string.Join(", ", function.Dependencies.Select(type => type.Name))}");
}

Dependencies are the types the factory asks for; a factory that takes the IServiceProvider reports only that.

Rules

  • Functions are scoped unless another lifetime is given: Lifetime on [Function], WithLifetime by hand.
  • Each delegate type can be registered once, and function names must be unique. Names can change until the catalog is built, so by hand the check runs when IFunctionCatalog is first resolved.
  • A registration is fixed once its function has been resolved or the catalog has been built: a later WithName, WithDescription, WithTags, WithLifetime or Decorate throws.
  • Missing dependencies fail when the function is first resolved, with the container's error as the inner exception (a factory that takes the IServiceProvider throws whatever its own code throws). Nothing is checked at startup unless ValidateFunctions is called, and the DI container remains responsible for validating the transitive dependency graph.
  • A scoped function must not be retained beyond its scope, and capturing a scoped service does not make that service thread-safe.
  • A singleton function must depend only on singletons: the container's scope validation, when it is on (it is by default in Development), reports a scoped dependency.

Composition

A factory depends on another function by declaring its delegate type as a parameter, so what an operation needs stays explicit:

[Function]
public static GetOrderSummary GetOrderSummary(GetOrderById getOrderById) => async (id, cancellationToken) =>
{
    var order = await getOrderById(id, cancellationToken);
    return order is null ? null : new OrderSummary(order.Id, order.Total);
};

The same serves when only some callers need a behaviour, such as a transaction around one operation: a function with a type of its own that calls the other one, instead of a decorator that every caller gets.

Decorators

Decorate wraps one function without changing its type, so every caller gets the wrapped version:

builder.Services.AddFunction<IOrderRepository, GetOrderById>(OrderFunctions.GetOrderById)
    .Decorate((inner, provider) =>
    {
        var logger = provider.GetRequiredService<ILogger<GetOrderById>>();
        return async (id, cancellationToken) =>
        {
            logger.LogDebug("Looking up order {OrderId}", id);
            return await inner(id, cancellationToken);
        };
    });

A decorator that needs no services takes only the inner function. Decorators wrap in the order they are added, so the last one runs first; they are applied when the function is created and receive the same IServiceProvider as the factory.

Many functions at once

AddFunctionDecorator puts one decorator in front of every function registered by the source generator, whatever its signature, or of the ones a filter accepts:

public sealed class Timing(ILogger<Timing> logger) : FunctionDecorator
{
    public override async Task<TResult> InvokeAsync<TResult>(FunctionInvocation invocation, Func<Task<TResult>> next)
    {
        var started = Stopwatch.GetTimestamp();
        try
        {
            return await next();
        }
        finally
        {
            logger.LogInformation("{Function} took {Elapsed}", invocation.Function.Name, Stopwatch.GetElapsedTime(started));
        }
    }
}

builder.Services.AddFunctionDecorator<Timing>();
builder.Services.AddFunctionDecorator<InTransaction>(function => function.Tags.Contains("write"));
  • A function that returns a Task, a Task<T>, a ValueTask or a ValueTask<T> goes through InvokeAsync; any other goes through Invoke. A function without a result has NoResult as its result.
  • FunctionInvocation gives the catalog entry of the function (Function), the services it was created with (Services) and the arguments of the call (Arguments, boxed only when read).
  • The decorator is a service, created with the function and from the same services: transient unless it is registered otherwise. The last one added runs first, and all of them run before the ones added with Decorate.
  • A function nobody decorates is the delegate its factory returned, with nothing in between.
  • The source generator writes the wrapper that makes this possible without reflection, so two kinds of function are left out: the ones registered by hand, and the ones whose signature a lambda cannot have (ref, in or out parameters, ref structs such as Span<T>).

Tracing and metrics

Two decorators come with the library, and take the same filter as any other. OpenTelemetry collects what they give from the source and the meter named FunctionInjection:

builder.Services.AddFunctionTracing();
builder.Services.AddFunctionMetrics();
builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing.AddSource(TracingFunctionDecorator.ActivitySourceName))
    .WithMetrics(metrics => metrics.AddMeter(MetricsFunctionDecorator.MeterName));
  • AddFunctionTracing: one span for each call, named after the function, with function.name and function.tags, marked as an error when the call throws.
  • AddFunctionMetrics: function.duration, a histogram in seconds with function.name and, for a call that throws, the type of the exception in error.type (the number of calls, the percentiles and the share of errors of a function come from it); and function.active, the calls in progress.

Tools for AI and MCP

The catalog already knows what a model needs to call a function: a name, a description, the parameters. Two more projects turn the functions a filter accepts into tools, without a wrapper for each.

[FunctionMetadata(Name = "orders.find", Description = "Finds an order by its number.", Tags = ["tool"])]
public delegate Task<Order?> FindOrder([Description("The number of the order.")] int number, CancellationToken cancellationToken);

// FunctionInjection.AI: for a chat client of Microsoft.Extensions.AI.
var tools = app.Services.GetFunctionTools(function => function.Tags.Contains("tool"));
var response = await chatClient.GetResponseAsync(messages, new ChatOptions { Tools = [.. tools] });

// FunctionInjection.Mcp: from an MCP server, next to the tools added in other ways.
builder.Services.AddMcpServer()
    .WithHttpTransport()
    .WithFunctionTools(
        function => function.Tags.Contains("tool"),
        (function, options) => options.ReadOnly = function.Tags.Contains("read"));
  • The name of the tool is the one of the function with the characters models accept (orders.find becomes orders_find); [Description] on a parameter of the delegate describes it to the model; the cancellation token is not a parameter of the tool.
  • The filter has no default: a tool is something a model can do, and each one is chosen. The second argument changes the options of each tool before it is made: its name, the hints of MCP, how the result is written.
  • A tool finds its function when it is called: in the scope of the MCP request, or in the services the chat client passes to the call (FunctionInvokingChatClient does), or else in the services the tools were made from. A scoped function needs one of them to be a scope.
  • A function that takes one request record gets one parameter that holds it: a tool with a few flat parameters is easier for a model, and is still better written by hand on top of the function.

Tests and startup

ReplaceFunction puts a given delegate in place of a registered function, decorators included; the function keeps its entry in the catalog. It throws when no function of that type is registered.

factory.WithWebHostBuilder(host => host.ConfigureTestServices(services =>
    services.ReplaceFunction<GetOrderById>((id, cancellationToken) => Task.FromResult<Order?>(fakeOrder))));

ValidateFunctions creates every registered function once, in a scope of its own, and throws an AggregateException listing all the ones that cannot be created. It runs the factories and the decorators, so singleton functions are created for good; scoped and transient ones are discarded with the scope.

app.Services.ValidateFunctions();

Native AOT

Factory invocation and service resolution use generic calls: the library does not inspect factory parameters or compile expression trees at run time, and IsAotCompatible enables the trimming and AOT analyzers for it. The two projects for the tools read the delegate with reflection, as the libraries they build on do: they are not for Native AOT.

Building

dotnet build
dotnet test
dotnet run -c Release --project benchmarks/FunctionInjection.Benchmarks -- --filter *
Folder Contents
src/FunctionInjection The library, for .NET 10 and .NET 11: no package dependencies on .NET 11, the abstractions of dependency injection on .NET 10
src/FunctionInjection.Generators The source generator, inside the package of the library
src/FunctionInjection.AI, src/FunctionInjection.Mcp The tools, with the packages of Microsoft.Extensions.AI and of the MCP SDK
tests/FunctionInjection.Tests The tests
tests/FunctionInjection.Tests.Library A project whose functions the tests register from outside, with [FunctionRegistrations]
benchmarks/FunctionInjection.Benchmarks The same operation as a service, a function, with MediatR and with Mediator: the results
  • Settings. What the projects share is in Directory.Build.props, the versions of the packages in Directory.Packages.props. The libraries are built with their XML documentation and the analyzers .NET recommends for code that others call.
  • Public API. The public surface of each library is listed in its PublicAPI.Unshipped.txt (and PublicAPI.Shipped.txt once a version is out): a change to it is a warning until the list says so, so it is always a choice. The diagnostics of the generator are listed the same way in AnalyzerReleases.*.md.
  • Source Link. The symbols point to the sources of the commit on GitHub, so that a debugger steps into the code the library was built from; on GitHub Actions the build is also deterministic, with no path of the machine inside.
  • CI. .github/workflows/ci.yml builds, tests on both versions of .NET and packs, for every push and pull request.

Releasing

The packages go to nuget.org from GitHub Actions, with trusted publishing: no API key is kept anywhere.

  1. Version in Directory.Build.props is the version of the three packages: 0.1.0-preview.1, then 0.1.0-preview.2 or 0.1.0.
  2. A tag with the same version, on a commit of main, publishes it: git tag v0.1.0-preview.1, then git push origin v0.1.0-preview.1.
  3. .github/workflows/publish.yml checks that the tag matches the version and that the commit is on main, then builds, runs the tests, packs and pushes the packages with their symbols.

A version on nuget.org cannot be deleted, only unlisted. Once a version is out, the entries of PublicAPI.Unshipped.txt move to PublicAPI.Shipped.txt and those of AnalyzerReleases.Unshipped.md to AnalyzerReleases.Shipped.md, and PackageValidationBaselineVersion makes package validation compare the next version with it.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed.  net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on FunctionInjection:

Package Downloads
FunctionInjection.AI

The functions of Function Injection as tools for a chat client of Microsoft.Extensions.AI: name, description and parameters from the catalog, no wrapper for each.

FunctionInjection.Mcp

The functions of Function Injection as tools of an MCP server, next to the tools added in other ways.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.0-preview.1 57 12/1/2026