Akka.NET can create C # actors in F # system?
I am trying to use some ReceiveActor
defined in the C # library in the F # system. I tried to create a non-F # API ActorSystem
, but the call system.ActorOf(Props.Create(fun () -> new CSharpActor()))
does not work as the function argument is incompatible.
I also couldn't find any documentation on the F # API pages on how to create actors defined in the C # library. Is it just not done? This is generally a "bad" design; Should the actor system be created in the library itself?
EDIT : the code I reproduce below
C # code
namespace CsActors {
using Akka.Actor;
using System;
public class CsActor : ReceiveActor {
public CsActor() {
Receive<string>(msg => { Console.WriteLine($"C# actor received: {msg}"); });
}
}
public class CsActorWithArgs : ReceiveActor {
public CsActorWithArgs(string prefix) {
Receive<string>(msg => { Console.WriteLine($"{prefix}: {msg}"); });
}
}
}
F # script
#I @"../build"
#r @"Akka.dll"
#r @"Akka.FSharp.dll"
#r @"CsActors.dll"
open Akka.Actor
open Akka.FSharp
open CsActors
let system = System.create "fcmixed" (Configuration.load())
// fails at runtime with "System.InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpressionN' to type 'System.Linq.Expressions.NewExpression'."
//let c1 = system.ActorOf(Props.Create(fun _ -> CsActor()))
// works if CsActor has constructor with no arguments
let c2 = system.ActorOf<CsActor> "c2"
c2 <! "foo"
// if actor doesn't have default constructor - this won't compile
//let c3 = system.ActorOf<CsActorWithArgs> "c3"
// Horusiath solution works for actors requiring arguments
let c4 = system.ActorOf(Props.Create(typeof<CsActorWithArgs>, [| box "c4-prefix" |]))
c4 <! "foo"
// Just for fun trying to use suggestion by dumetrulo (couldn't quite get it to work...)
// copied Lambda module from http://www.fssnip.net/ts/title/F-lambda-to-C-LINQ-Expression
//module Lambda =
// open Microsoft.FSharp.Linq.RuntimeHelpers
// open System.Linq.Expressions
// let toExpression (``f# lambda`` : Quotations.Expr<'a>) =
// ``f# lambda``
// |> LeafExpressionConverter.QuotationToExpression
// |> unbox<Expression<'a>>
//let c5 = system.ActorOf(Props.Create(<@ (fun _ -> CsActorWithArgs "c5-prefix") @> |> Lambda.toExpression))
//c5 <! "foo"
source to share
Props.Create
with a function won't work, because what Props.Create(() => new Actor(a, b))
in C # actually takes an expression and deconstructs it into type and constructor arguments. This is necessary because one of the requirements for a props is that it must be serializable.
What you can do is use another overload Props.Create(typeof<MyActor>, [| box myArg1; box myArg2 |])
that essentially does the same thing, without compile-time type safety.
That being said, it would be better if you just use Akkling or the Akka.FSharp API if possible.
source to share