Skip to content

Instantly share code, notes, and snippets.

@ninjarobot
Created May 2, 2022 17:49
Show Gist options
  • Save ninjarobot/20ff888d486355e32099e1ad5567982a to your computer and use it in GitHub Desktop.
Save ninjarobot/20ff888d486355e32099e1ad5567982a to your computer and use it in GitHub Desktop.
Basic IoC using DI in F#
#r "nuget: Microsoft.Extensions.DependencyInjection"
#r "nuget: Microsoft.Extensions.Hosting"
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Hosting
type Foo = { Foo : string }
type Bar = { Bar : int }
type FooBar = Foo -> Bar
let fubar : FooBar =
fun (foo:Foo) ->
{ Bar = System.Int32.Parse foo.Foo }
type IServiceCollection with
member this.AddFooBar() =
this.AddSingleton<FooBar>(fubar)
let host =
Host.CreateDefaultBuilder(fsi.CommandLineArgs)
.ConfigureServices(fun services -> services.AddFooBar() |> ignore<IServiceCollection>)
.Build()
let myFubar = host.Services.GetRequiredService<FooBar>()
myFubar { Foo = "42" } |> printfn "%A"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment