queil / fsc-host

Extend your F# apps with F# scripts
The Unlicense
26 stars 1 forks source link

fsc-host Build Status NuGet Badge Coverage

Extend your F# apps with F# scripts

You can easily extend your applications by calling functions and retrieving values on run time from dynamically compiled scripts. A bare minimum example (Plugin API):

plugins/default/plugin.fsx (Plugin)
let plugin (s:string) = printfn $"HELLO: %s{s}"
Program.fs (Host)
let myWriter =
  plugin<string -> unit> {
    load
  } |> Async.RunSynchronously

myWriter $"I hereby send the message"
Output
HELLO: I hereby send the message

What is supported

Requirements

Warning

This project is still in v0 which means the public API hasn't stabilised yet and breaking changes may happen between minor versions. Breaking changes are indicated in the release notes in GitHub releases.

Example (Basic API)

  1. Create a console app and add the package
dotnet new console -lang F# --name fsc-host-test && cd fsc-host-test && dotnet add package Queil.FSharp.FscHost --version 0.16.0
  1. Save the below as script.fsx:
let helloFromScript name = sprintf "HELLO FROM THE SCRIPT, %s" name

let myPrimes = [2; 3; 5]
  1. In your Program.cs:
open Queil.FSharp.FscHost

try

  // compile a script and retrieve two properties out of it
  let getScriptProperties () =
    File "script.fsx"
    |> CompilerHost.getMember2 Options.Default
         (Member<string -> string>.Path "Script.helloFromScript")
         (Member<int list>.Path "Script.myPrimes")

  let (helloWorld, primesOfTheDay) = getScriptProperties () |> Async.RunSynchronously

  let myName = "Console Example"

  myName |> helloWorld |> printfn "%s"

  printfn "Primes of the day: "
  primesOfTheDay |> Seq.iter (printfn "%i")

with
// you can handle more exceptions from the CompilerHost here
| ScriptMemberNotFound(name, foundMembers) ->
  printfn "Couldn't find member: '%s'" name
  printfn "Found members: "
  foundMembers |> Seq.iter(printfn "%s")
  1. You should get the following output when dotnet run:
HELLO FROM THE SCRIPT, Console Example
Primes of the day: 
2
3
5

APIs

The public API of this library comes in three flavours:

Known issues

Resources

Development

Fix FSharp.Core package hash locally:

docker run --rm -it  -v $(pwd):/build -w /build  mcr.microsoft.com/dotnet/sdk:8.0 dotnet restore --force-evaluate