Azure Service Fabric:使用无状态服务将数据存储到有状态服务(c#编程)

时间:2017-11-28 15:00:30

标签: c# azure-service-fabric

目标:想要在stateless服务中创建包含某些实体的产品,并且创建的产品应存储在stateful服务中(IReliableDictionary

// Task done: I am working with Azure Service Fabric. Firstly, I created a 
// stateful service which does the job of AddProduct and GetAllProducts and the 
// data is stored in IReliableDictionary. For this I have declared, and passed 
// the object in a constructor.

private readonly IReliableStateManager _stateManager;
public ServiceFabricRepository(IReliableStateManager stateManager)
{
   _stateManager = stateManager;
}

如果我在stateful服务中添加产品,则会将产品添加到数据库中(IReliableDictionary)。这是经过测试和运作的。

接下来的任务,我所做的是在解决方案中添加一项新服务(stateless)。 stateless应该创建包含某些实体的产品(IdName)。创建的产品应添加到我的数据库(stateful服务)

问题:我能够使用某些实体创建产品,但产品未添加到我的数据库中,因为它要求我在IReliableStateManager服务中创建stateless的实例, stateManager始终为null

如何在IReliableStateManager服务中创建stateless的实例 因为IReliableStateManagerstateful服务继承提供 层次结构。我正在stateless服务

中创建我的存储库实例
//(stateManager is never assigned to and will always have its dafult value null) 
private static IReliableStateManager stateManager; 
private ServiceFabricRepository = new ServiceFabricRepository(stateManager)

我做了一些搜索,发现stateful服务用于数据存储(示例接口:AddProductGetProduct)和stateless Web Api用于公开使用服务远程处理的stateful服务接口或用于服务之间通信的Http接口。但无法为我的方案找到任何示例。

对任何帮助或建议都非常有帮助

谢谢&此致

1 个答案:

答案 0 :(得分:2)

您不在Stateless服务中直接使用IReliableStateManager,而是从Stateless调用Stateful服务,并且需要保存传递​​对象。

例如: 在无状态服务中创建有状态服务的服务代理并调用其方法:

IProductService = ServiceProxy.Create<IProductService>(new Uri("fabric:/SfSample/ProductService"), new ServicePartitionKey(0));
var newProduct = new Product()
{
    Name = product.Name,
    Id = product.Id
};
await _productService.AddProduct(newProduct);

有状态服务:

public class ProductService : StatefulService, IProductService
    {

        public async Task AddProduct(Product product)
        {
            var products = await StateManager.GetOrAddAsync<IReliableDictionary<Guid, Product>>("products");

            using (var tx = StateManager.CreateTransaction())
            {
                await products.AddOrUpdateAsync(tx, product.Id, product, (id, value) => product);

                await tx.CommitAsync();
            }
        }
...........
}
相关问题