top of page

C#: Interfaces to Functions, With FuncR

FuncR is a small .NET standard library that enables you to register functions against interfaces in C#.

In short, it allows you to go from this:

Into something like this:

FuncR uses a DispatchProxy to generate a proxy class that instantiates the interface at runtime and hooks up the registered functions to the interface methods.

This allows you to inject the interface into your services and use it like any other service in your domain.

Let’s put this all together inside a .NET console app!

Create a new Console app (in .NET Core 2, 3 or .NET 5):

mkdir Your.First.Function
cd Your.First.Function
dotnet new console

Add the FuncR package:

dotnet add package FuncR

Write the implementation:

using System;
using FuncR;
using Microsoft.Extensions.DependencyInjection;

namespace Your.First.Function
    // We don't need no, implementation
    public interface IFooService    
        string Foo (int numberOfFoos);    
    class Program    
        static void Main(string[] args)        
            var services = new ServiceCollection();
                // string Foo(int numberOfFoos)                
                .Runs<int, string>(numberOfFoos=>                
                        return "Too many foos!";
                    return $"This many foos: '{numberOfFoos}'";                
             var fooService=
             // Prints: "This many foos: '3'"
             // Prints: "Too many foos!"

Run the implementation:

dotnet run

dotnet run output

Details of the example

Line #8 sets up the stage for our service interface.

Line #19 registers the proxy for IFooService

Line #20 registers the function pointer for the name “Foo” on the proxy

Lines #22-28 registers the actual implementation of the function for the proxy in the form of <TParameter1Type, TReturnType>, like any C# Func

Line #30 resolves our registered service from the Dependency Injection container.

Lines #34 and #36 call upon the proxy, which will look up the registered function and invoke it.

Source: Medium

The Tech Platform

bottom of page