From 58aa302f49311475cce11dcbd477df217e790ea6 Mon Sep 17 00:00:00 2001 From: Joel Stålnacke Date: Fri, 13 Feb 2026 20:48:51 +0200 Subject: Initial commit --- ...onalObjects.Examples.DependencyInjection.fsproj | 16 +++++++ examples/DependencyInjection/Program.fs | 51 ++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 examples/DependencyInjection/FunctionalObjects.Examples.DependencyInjection.fsproj create mode 100644 examples/DependencyInjection/Program.fs (limited to 'examples/DependencyInjection') diff --git a/examples/DependencyInjection/FunctionalObjects.Examples.DependencyInjection.fsproj b/examples/DependencyInjection/FunctionalObjects.Examples.DependencyInjection.fsproj new file mode 100644 index 0000000..806da26 --- /dev/null +++ b/examples/DependencyInjection/FunctionalObjects.Examples.DependencyInjection.fsproj @@ -0,0 +1,16 @@ + + + + Exe + net10.0 + + + + + + + + + + + diff --git a/examples/DependencyInjection/Program.fs b/examples/DependencyInjection/Program.fs new file mode 100644 index 0000000..84b51c6 --- /dev/null +++ b/examples/DependencyInjection/Program.fs @@ -0,0 +1,51 @@ +open System + +type Logger = { + Log : string -> unit +} + +type HelloService = { + SayHelloTo : string -> unit +} + +// This is the constructor of a logger that adds a timestamp in the specified +// format to each log message it writes. +let dateTimeLogger (dateFormat : string) = + { Log = + fun msg -> + let timestamp = DateTime.Now.ToString dateFormat + printfn "[%s]: %s" timestamp msg } + +let logger = dateTimeLogger "yyyy-MM-dd hh:mm:ss" + +// This implementation of Logger ignores all messages +let noopLogger = + { Log = ignore } + +let doSomething logger = + logger.Log "Starting to do something" + let x = 1 + 1 + sprintf "Did something! Result: %d" x + |> logger.Log + +// Implementations can be injected to application code +doSomething logger +doSomething noopLogger + +// Implement HelloService. Our implementation depends on a Logger to write +// messages to. +let helloService logger = + { SayHelloTo = + fun user -> + sprintf "Saying hi to %s" user + |> logger.Log + printfn "Hi %s!" user + logger.Log "Operation complete" } + +// Create an instance of helloService. +// +// We don't want to do anything with the messages so we discard them by using +// injecting noopLogger as the implementation of Logger. +let instance = helloService noopLogger + +instance.SayHelloTo "John" -- cgit v1.2.3