-
-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathActorController.cs
More file actions
76 lines (59 loc) · 2.09 KB
/
ActorController.cs
File metadata and controls
76 lines (59 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// -----------------------------------------------------------------------
// <copyright file="ActorController.cs" company="Asynkron AB">
// Copyright (C) 2015-2024 Asynkron AB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Proto;
using Proto.DependencyInjection;
namespace DependencyInjection.Controllers;
public class DependencyInjectedActor : IActor
{
private readonly ILogger<DependencyInjectedActor> _logger;
public DependencyInjectedActor(ILogger<DependencyInjectedActor> logger)
{
//dependency injected arguments here
_logger = logger;
}
public Task ReceiveAsync(IContext context) =>
context.Message switch
{
HelloRequest msg => OnHelloMessage(msg, context),
_ => Task.CompletedTask
};
private Task OnHelloMessage(HelloRequest msg, IContext context)
{
_logger.LogInformation("Got request");
var greeting = $"Hello to you {msg.Name}";
context.Respond(new HelloResponse(greeting));
return Task.CompletedTask;
}
}
public record HelloRequest(string Name);
public record HelloResponse(string Greeting);
[ApiController]
[Route("[controller]")]
public class ActorController : ControllerBase
{
private readonly ActorSystem _actorSystem;
public ActorController(ActorSystem actorSystem)
{
_actorSystem = actorSystem;
}
[HttpGet]
public async Task<string> Get()
{
//Get props for dependency injected actor
var props = _actorSystem.DI().PropsFor<DependencyInjectedActor>();
//spawn the actor
var pid = _actorSystem.Root.Spawn(props);
//send a request and await the response
var response = await _actorSystem.Root.RequestAsync<HelloResponse>(pid, new HelloRequest("Proto.Actor"));
//stop the actor
await _actorSystem.Root.StopAsync(pid);
//return the result
return response.Greeting;
}
}