© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
11 replies
pedroavila

❔ Persist a record with Akka.Net

I have created an actor that calls to the service the create method which calls the same method that is in the repository
public class UserActor : ReceiveActor
{
    private readonly IServiceScope _scope;
    private readonly IUserActorService _userActorService;

    public UserActor(IServiceProvider serviceProvider)
    {
        _scope = serviceProvider.CreateScope();
        _userActorService = _scope.ServiceProvider.GetRequiredService<IUserActorService>();

        Receive<CreateUserMessage>(message =>
        {
            var user = message.User;
            _userActorService.Create(user);
        });
    }
}
public class UserActor : ReceiveActor
{
    private readonly IServiceScope _scope;
    private readonly IUserActorService _userActorService;

    public UserActor(IServiceProvider serviceProvider)
    {
        _scope = serviceProvider.CreateScope();
        _userActorService = _scope.ServiceProvider.GetRequiredService<IUserActorService>();

        Receive<CreateUserMessage>(message =>
        {
            var user = message.User;
            _userActorService.Create(user);
        });
    }
}

Program
using (var serviceScope = host.Services.CreateScope())
{
    var actorSystem = serviceScope.ServiceProvider.GetService<ActorSystem>();
    var userActorService = serviceScope.ServiceProvider.GetRequiredService<IUserActorService>();
    var userActor = actorSystem.ActorOf(Props.Create(() => new UserActor(userActorService)), "userActor");

    var createUserMessage = new CreateUserMessage(new User()
    {
        Name = "Pedro Avila",
        Age = 46
    });
    
    userActor.Tell(createUserMessage);
}
using (var serviceScope = host.Services.CreateScope())
{
    var actorSystem = serviceScope.ServiceProvider.GetService<ActorSystem>();
    var userActorService = serviceScope.ServiceProvider.GetRequiredService<IUserActorService>();
    var userActor = actorSystem.ActorOf(Props.Create(() => new UserActor(userActorService)), "userActor");

    var createUserMessage = new CreateUserMessage(new User()
    {
        Name = "Pedro Avila",
        Age = 46
    });
    
    userActor.Tell(createUserMessage);
}

The error I get is that an actor cannot be created with new
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Demo application architecture with akka.net
C#CC# / help
3y ago
❔ Akka.net Actors are not responding in time
C#CC# / help
3y ago
Need a hand with Asp.net MVC Net7.
C#CC# / help
2y ago
❔ ASP.NET Core Persist Task between requests
C#CC# / help
4y ago