- C# 98.9%
- PowerShell 0.5%
- Shell 0.3%
- Dockerfile 0.3%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
|
|
||
| .config | ||
| .github | ||
| docs | ||
| perf/MicroBenchmark | ||
| src | ||
| test | ||
| .editorconfig | ||
| .gitattributes | ||
| .gitignore | ||
| AGENTS.md | ||
| Directory.Build.props | ||
| Directory.Packages.props | ||
| global.json | ||
| Icon.png | ||
| LICENSE | ||
| Multicaster.sln.DotSettings | ||
| Multicaster.slnx | ||
| opensource.snk | ||
| README.md | ||
Multicaster
This framework provides a proxy for transparently invoking methods of multiple POCO instances or remote clients through an interface.
For instance, a single call to IGreeter.Hello can invoke methods on several objects or broadcast the call to remote clients like those using MagicOnion or SignalR.
The framework incorporates the concept of groups that bundle together the receivers (targets) to enable transparent invocation, allowing receivers to be added or removed flexibly from the group for ease of management.
Usage
Basic Usage
A Group is requested from IMulticastGroupProvider by specifying a name, key type, and calling interface. If the Group does not exist, it will be created when it is requested.
There are synchronous and asynchronous operation versions of the Group, which can be selected according to the use case and supported functions.
public interface IGreeterReceiver
{
void OnMessage(string sender, string message);
}
public class GreeterReceiver(string name) : IGreeterReceiver
{
public void OnMessage(string sender, string message)
=> Console.WriteLine($"[{name}] <{sender}> {message}")
}
var group = groupProvider.GetOrAddSynchronousGroup<Guid, IGreeterReceiver>("MyGroup");
You can register a receiver instance that implements the interface for the call with the key to the retrieved Group.
var receiverId = Guid.NewGuid();
group.Add(receiverId, receiver);
Note
In the case of MagicOnion, you can register the
Clientproperty that can be used in StreamingHub.
You get a proxy object that calls the receiver via the Group's properties and methods such as All, Except, Only, and Single, and you can call the methods.
group.All.OnMessage("A", "Hello");
Groups can be deleted from memory by calling Dispose.
group.Dispose();
Note
Note that this means that in-memory groups are completely deleted, but if Redis/NATS is used as the backplane, they are only deleted from memory on the .NET server that called it, and not from other servers.
In-Memory (Plain Old CLR Object)
Multicaster allows you to call the methods of multiple instances at once.
For example, it is possible to call multiple instances that implement IGreeterReceiver.OnMessage at once. The code below is an example of this.
public interface IGreeterReceiver
{
void OnMessage(string sender, string message);
}
public class GreeterReceiver(string name) : IGreeterReceiver
{
public void OnMessage(string sender, string message)
=> Console.WriteLine($"[{name}] <{sender}> {message}")
}
// Create receivers.
var receiverA = new GreeterReceiver("A");
var receiverIdA = Guid.NewGuid();
var receiverB = new GreeterReceiver("B");
var receiverIdB = Guid.NewGuid();
var receiverC = new GreeterReceiver("C");
var receiverIdC = Guid.NewGuid();
// Create a in-memory group provider.
var groupProvider = new InMemoryGroupProvider(DynamicInMemoryProxyFactory.Instance);
// Create a group and add receivers to the group.
using var group = groupProvider.GetOrAddSynchronousGroup<Guid, IGreeterReceiver>("MyGroup");
group.Add(receiverIdA, receiverA);
group.Add(receiverIdB, receiverB);
group.Add(receiverIdC, receiverC);
// Call receivers via proxy.
group.All.OnMessage("System", "Hello");
group.Except([receiverIdA]).OnMessage("System", "Hello without A");
// Call the receiver directly. (Normal method call)
receiverA.OnMessage("DirectMessage", "Sent a message to the receiver directly.");
Outputs
[A] <System> Hello
[B] <System> Hello
[C] <System> Hello
[B] <System> Hello without A
[C] <System> Hello without A
[A] <DirectMessage> Sent a message to the receiver directly.
Broadcasts and client results
Use receiver methods returning void for broadcasts through All, Except, or Only.
Methods returning Task or Task<T> are client results calls: they wait for a response from a specific receiver, even when the task has no result value. Use Single(receiverId) to invoke these methods on transports that support client results.
public interface IDashboardReceiver
{
// Notify dashboards of a status change.
void OnStatusChanged(string status);
// Wait for one dashboard to finish refreshing.
Task RefreshAsync();
}
// Notify all dashboards.
group.All.OnStatusChanged("Ready");
// Refresh a specific dashboard and wait for completion.
await group.Single(receiverId).RefreshAsync();
Calling a client results method through All or Except throws NotSupportedException, even if the group is empty or only one receiver remains after filtering. Merely removing await does not turn a Task-returning receiver method into a broadcast; its interface return type must be void.
For MagicOnion, Client can also be used to call a client results method on the current client. See Client Results for its requirements and limitations.
API
IMulticastGroupProvider interface
IMulticastAsyncGroup<TKey, TReceiver> GetOrAddGroup<TKey, TReceiver>(string name);IMulticastSyncGroup<TKey, TReceiver> GetOrAddSynchronousGroup<TKey, TReceiver>(string name);
IMulticastGroup<TKey, T> interface
TReceiver All { get; }TReceiver Except(IEnumerable<TKey> excludes);TReceiver Only(IEnumerable<TKey> targets);TReceiver Single(TKey target);void Dispose()- Dispose and unregister the group from a group provider.
IMulticastAsyncGroup<TKey, T> interface (implements IMulticastGroup<TKey, T>)
ValueTask AddAsync(TKey key, TReceiver receiver, CancellationToken cancellationToken = default);ValueTask RemoveAsync(TKey key, CancellationToken cancellationToken = default);ValueTask<int> CountAsync(CancellationToken cancellationToken = default);
IMulticastSyncGroup<TKey, T> interface (implements IMulticastGroup<TKey, T>)
void Add(TKey key, TReceiver receiver);void Remove(TKey key);int Count();
NativeAOT and source-generated proxies
For NativeAOT, reference Multicaster.SourceGenerator and declare receiver interfaces on a partial class:
<PackageReference Include="Multicaster" Version="x.y.z" />
<PackageReference Include="Multicaster.SourceGenerator" Version="x.y.z" PrivateAssets="all" />
[MulticasterGeneration(typeof(IGreeterReceiver))]
public partial class MulticasterGenerated
{
}
var groupProvider = new InMemoryGroupProvider(MulticasterGenerated.InMemoryProxyFactory);
The generator adds InMemoryProxyFactory and RemoteProxyFactory. The class must be top-level, non-generic, and not file-local.
Combine factories from multiple assemblies with composite factories:
var inMemoryFactory = new CompositeInMemoryProxyFactory(
[FeatureA.InMemoryProxyFactory, FeatureB.InMemoryProxyFactory]);
var remoteFactory = new CompositeRemoteProxyFactory(
[FeatureA.RemoteProxyFactory, FeatureB.RemoteProxyFactory]);
Composite factories try each candidate's TryCreate in order. Optional dynamic fallbacks are supported only in JIT applications, not NativeAOT.
Reusing code generation
Custom source generators can embed Multicaster's Roslyn-independent model, validation, method-ID calculation, and emitter using the source-only package (requires C# 11+):
<PackageReference Include="Multicaster.CodeGen.Source" Version="x.y.z" PrivateAssets="all" />
Adapters must use fully qualified, closed type names, normalize dynamic to object, and set ReceiverMethodDefinition.DeclaringTypeName for inherited methods (defaults to the receiver root). Each inherited method needs a distinct method ID; named MethodId arguments take precedence over constructor arguments.
Transports and supported features
| Transport | Multicast | Synchronous | Count/CountAsync | Client Results |
|---|---|---|---|---|
| InMemory | ✔️ | ✔️ | ✔️ | ✔️ |
| Remote (InMemory) | ✔️ | ✔️ | ✔️ | ✔️ |
| Redis | ✔️ | ✔️ | - | - |
| NATS | ✔️ | ✔️ | - | - |