C#: Interfaces to Functions, With FuncR
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):
dotnet new console
Add the FuncR package:
dotnet add package FuncR
Write the implementation:
Run the implementation:
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
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.
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.