如何在 Azure Service Fabric ASP.NET 核心有状态服务中获取 PartitionInfo?

How to obtain PartitionInfo in an Azure Service Fabric ASP.NET Core stateful service?

我们如何访问有状态服务的控制器 class 中的 ParitionInfo 对象?

这里是对象的link: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 核心有状态服务中的服务定义,其中对象可以很容易地从定义它的基 class 中获取:

    /// <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();
                    }))
            };
        }

我是否应该创建一个单例 class,通过 DI 将其连接起来,然后让 DI 框架将其实例传递给控制器​​ class?有没有更好的捷径来达到访问ParitionInfo数据的目的?

你走在正确的道路上。将参数 IStatefulServicePartition 添加到 MyConntroller 构造函数。 在 ConfigureServices 中,使用 this.Partition.

注册服务 partition

例如:

.AddSingleton<IStatefulServicePartition>(this.Partition)