C#: Interfaces to Functions, With FuncR

Maarten Merken
Geek Culture
Published in
3 min readMar 30, 2021

--

I find myself often in need of extracting a certain method into an entirely new service. This new service now has the sole purpose of housing that method.

This is mostly the case when working with code that communicates with infrastructure (logging, files, network, API’s). This code is mostly static and does not require a whole new service implementation. But, nevertheless a new class needs to becreated to hold this functionality.

I started looking for the most concise form of writing that functionality, without the need of introducing a new service implementation class, an interface to a function, sort of speak…

The result of this work has been packaged into a small library called FuncR, allow me to elaborate…

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:

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.

📚Documentation

FuncR comes with extensive documentation and sample projects to help you get started!

This includes, service resolution through dependency injection, async functions and nested functions.

--

--