Dynamically create an object from Actor class within cli

Hello everybody!

Is there any way to create an instance of an actor class from command line?
I mean dfx ...

Yes. If the motoko code declares an actor class, then you can manually pass an argument to
dfx canister install ... the same way you pass arguments to call (I think).

Will see if I can find an example…

dfx new MyClass
cd MyClass

Edit file src/MyClass/main.mo to contain the actor class:

actor class (greeting : Text) {

   public func greet(name : Text) : async Text {
        return greeting # " " # name # "!";
    };

};

Now do:

dfx start --background
dfx canister create MyClass
dfx build MyClass
dfx canister install MyClass --argument '("Hallo")'
dfx canister call MyClass greet '("Claudio")'
dfx canister install MyClass --argument '("Ciao")' --mode reinstall
dfx canister call MyClass greet '("Claudio")'

Truth be told, at the moment, dfx doesn’t seem well suited to creating multiple instances of an actor class.

For that, I’d recommend using a Motoko actor that imports an actor class as a library and instantiates it programmatically, along the lines of the example here:

Word of warning though: that example should also be passing some cycles each time it instantiates an actor and currently does not. If I get a chance, I’ll turn that into another, buildable, example, adding cycle management, in the collection of examples here:

3 Likes