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

问题描述 投票:1回答:1

我们如何在有状态服务的Controller类中访问ParitionInfo对象?

这是对象的链接: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 Core有状态服务中的服务定义,其中可以从定义它的基类轻松获取对象:

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

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

c# azure asp.net-core azure-service-fabric
1个回答
2
投票

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

例如:

.AddSingleton<IStatefulServicePartition>(this.Partition)
© www.soinside.com 2019 - 2024. All rights reserved.