代码之家  ›  专栏  ›  技术社区  ›  Arash

如何在Azure服务结构中获取PartitionInfoASP.NET核心有状态服务?

  •  1
  • Arash  · 技术社区  · 6 年前

    https://docs.microsoft.com/en-us/dotnet/api/system.fabric.servicenotification.partitioninfo?view=azure-dotnet

    public class MyConntroller : ControllerBase
    {
      [HttpPost]
      public async Task<IActionResult> Save(MyObject obj)
      {
         //Here I would like to access ParitionInfo object. How?!
      }
    }
    

    下面是ASP.NET核心有状态服务,可从定义对象的基类轻松获取对象:

        /// <summary>
        /// The FabricRuntime creates an instance of this class for each service 
        /// type instance. 
        /// </summary>
        internal sealed class MyStatefulService : StatefulService
        {
            public MyStatefulService(StatefulServiceContext context)
                : base(context)
            { }
    
            /// <summary>
            /// Optional override to create listeners (like tcp, http) for this service instance.
            /// </summary>
            /// <returns>The collection of listeners.</returns>
            protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
            {
                return new ServiceReplicaListener[]
                {
                    new ServiceReplicaListener(serviceContext =>
                        new KestrelCommunicationListener(serviceContext, (url, listener) =>
                        {
                            ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");
    
                            return new WebHostBuilder()
                                        .UseKestrel()
                                        .ConfigureServices(
                                            services => services
                                                .AddSingleton<StatefulServiceContext>(serviceContext)
                                                .AddSingleton<IReliableStateManager>(this.StateManager))
                                        .UseContentRoot(Directory.GetCurrentDirectory())
                                        .UseStartup<Startup>()
                                        .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.UseUniqueServiceUrl)
                                        .UseUrls(url)
                                        .Build();
                        }))
                };
            }
    

    我是否应该创建一个singleton类,通过DI将其连接起来,并让DI框架将其实例传递给controller类?有没有更好的快捷方式来实现访问ParitionInfo数据的目标?

    1 回复  |  直到 5 年前
        1
  •  2
  •   LoekD    6 年前

    你走对了路。添加参数 IStatefulServicePartition 给你的 MyConntroller 建造师。 ConfigureServices ,注册服务 partition this.Partition .

    例如:

    .AddSingleton<IStatefulServicePartition>(this.Partition)