Skip to content

Instantly share code, notes, and snippets.

@ReubenBond
Created March 20, 2022 19:36
Show Gist options
  • Save ReubenBond/8f14546c69ffc39efe8f47fe8140b4df to your computer and use it in GitHub Desktop.
Save ReubenBond/8f14546c69ffc39efe8f47fe8140b4df to your computer and use it in GitHub Desktop.
Orleans grain observer (IGrainObserver) which returns results
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>ObserverWithReturn</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Orleans.CodeGenerator.MSBuild" Version="3.6.0" />
<PackageReference Include="Microsoft.Orleans.Server" Version="3.6.0" />
</ItemGroup>
</Project>
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Orleans;
using Orleans.Hosting;
namespace ObserverWithReturn;
class Program
{
static async Task Main(string[] args)
{
using var host = Host.CreateDefaultBuilder()
.UseOrleans(siloBuilder =>
{
siloBuilder.UseLocalhostClustering();
}).Build();
await host.StartAsync();
var client = host.Services.GetRequiredService<IGrainFactory>();
var observer = new MyObserver("Hope this is what you're after.");
var observerReference = await client.CreateObjectReference<IMyObserver>(observer);
var grain = client.GetGrain<IMyGrain>("testing");
var result = await grain.CallMeBack(observerReference);
Console.WriteLine($"Client received: \"{result}\"");
Console.ReadLine();
await host.StopAsync();
}
}
public interface IMyObserver : IGrainObserver
{
ValueTask<string> GetGreeting(string input);
}
public class MyObserver : IMyObserver
{
private readonly string _customMessage;
public MyObserver(string customMessage) => _customMessage = customMessage;
public ValueTask<string> GetGreeting(string input) => new($"Hello {input}! {_customMessage}");
}
public interface IMyGrain : IGrainWithStringKey
{
Task<string> CallMeBack(IMyObserver observer);
}
public class MyGrain : Grain, IMyGrain
{
public async Task<string> CallMeBack(IMyObserver observer)
{
var result = await observer.GetGreeting(this.GetPrimaryKeyString());
return $"Grain received: \"{result}\"";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment