From 4767ec0056d8fa27ef31cfe2d48e799acaf2cc5b Mon Sep 17 00:00:00 2001 From: Roger Johansson Date: Mon, 17 Oct 2022 10:25:48 +0200 Subject: [PATCH] di enabled cluster setup (#1823) --- .../ServiceCollectionExtensions.cs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/Proto.Cluster/ServiceCollectionExtensions.cs b/src/Proto.Cluster/ServiceCollectionExtensions.cs index 30c897eb4b..d0090e493a 100644 --- a/src/Proto.Cluster/ServiceCollectionExtensions.cs +++ b/src/Proto.Cluster/ServiceCollectionExtensions.cs @@ -11,9 +11,60 @@ namespace Proto.Cluster; +[PublicAPI] +public class HostedClusterConfig +{ + public string ClusterName { get; set; } = "MyCluster"; + public string BindToHost { get; set; }= "localhost"; + public int Port{ get; set; } = 0; + public Func? ConfigureSystem { get; set; } + public Func? ConfigureRemote { get; set; } + public Func? ConfigureCluster { get; set; } + public IClusterProvider? ClusterProvider { get; set; } + public IIdentityLookup? IdentityLookup { get; set; } + public bool RunAsClient { get; set; } +} + [PublicAPI] public static class ServiceCollectionExtensions { + public static IServiceCollection AddProtoCluster(this IServiceCollection self, Action configure) + { + var boot = new HostedClusterConfig(); + self.AddSingleton(p => + { + var loggerFactory = p.GetRequiredService(); + Log.SetLoggerFactory(loggerFactory); + + + configure(p, boot); + + var s = new ActorSystemConfig(); + s = boot.ConfigureSystem?.Invoke(s) ?? s; + + var r = GrpcNetRemoteConfig.BindTo(boot.BindToHost, boot.Port); + r = boot.ConfigureRemote?.Invoke(r) ?? r; + boot.ClusterProvider ??= new SeedNodeClusterProvider(); + boot.IdentityLookup ??= new PartitionIdentityLookup(); + + var c = ClusterConfig.Setup(boot.ClusterName, boot.ClusterProvider, boot.IdentityLookup); + c = boot.ConfigureCluster?.Invoke(c) ?? c; + + var system = new ActorSystem(s) + .WithRemote(r) + .WithCluster(c) + .WithServiceProvider(p); + + return system; + }); + + self.AddSingleton(p => p.GetRequiredService().Cluster()); + self.AddSingleton(p => p.GetRequiredService().Root); + self.AddHostedService(p => new ProtoActorLifecycleHost(p.GetRequiredService(), boot.RunAsClient)); + + return self; + } + public static IServiceCollection AddProtoCluster(this IServiceCollection self, string clusterName, string bindToHost = "localhost", int port = 0, Func? configureSystem = null,