F# interactive services: how to pass in .NET objects from host

f#

Solution

This would be a great addition to the API exposed by the F# Interactive services!

I guess the easiest workaround would be to define some collection for storing the parameters you want to pass in inside the F# interactive session:

let parameters = new System.Collections.Generic.Dictionary<string, obj>()

Then you can use `EvalExpression` to get a function that stores a value in the dictionary:

(fun k v -> parameters.Add(k, v))

The host can then cast the returned object to `string -> obj -> unit` and use it to set parameters that will be accessible in the code running inside the service..

EDIT: For some reason, unknown to me, the above does not quite work. However, you can wrap the F# function in a .NET delegate and then it works OK. Alternatively, you can just evaluate the expression `parameters` and get back the whole dictionary (and then you can store the values there directly).

This did the trick for me:

fsiSession.EvalInteraction
  ("let env = new System.Collections.Generic.Dictionary<string, obj>()")
fsiSession.EvalExpression
  ("System.Action<string, obj>(fun k v -> env.Add(k, v))")

Problem

I'm using the F# CompilerServices to host a .NET scripting environment in my app, similar to the example here: https://github.com/fsharp/FSharp.Compiler.Service/blob/master/samples/InteractiveService/Program.fs If I evaluate an expression (`EvalExpression`) the data is marshalled back into the host app, but there is no obvious way to pass data in the opposite direction. How can I pass .NET objects from the host app into the script environment?

Original source