Reputation: 11
Objective: Want to create a product with some entities in a stateless
service and the created product should get stored in a stateful
service (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;
}
If I am adding a product within a stateful
service the product is being added into the database (IReliableDictionary
). This is tested and its working.
The next task, what I did is add a new service (stateless
) in the solution. The stateless
should create a product with some entities (Id
, Name
). The product created should be added in my database (stateful
service)
Problem: I am able to create the product with some entities but the product is not being added in my database, because it is asking me to create an instance of IReliableStateManager
in the stateless
service and the stateManager
is always null
.
How to create an instance of IReliableStateManager
in a stateless
service
since IReliableStateManager
is provided by the stateful
service inheritance
hierarchy. I am creating an instance of my repository in a stateless
service
//(stateManager is never assigned to and will always have its dafult value null)
private static IReliableStateManager stateManager;
private ServiceFabricRepository = new ServiceFabricRepository(stateManager)
I have done some search and found out that stateful
service is used for data storage( Example interfaces: AddProduct
or GetProduct
) and stateless Web Api
is used to expose the interfaces of stateful
service using service remoting or Http
for communication between the services. But was unable to find any example for my scenario.
Will be very helpful for any help or suggestions
Thanks & Regards
Upvotes: 1
Views: 1010
Reputation: 2062
You do not use IReliableStateManager directly in Stateless service, rather call Stateful service from Stateless and pass object needs to be saved.
For example: Create service proxy of stateful service in stateless service and call its method:
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);
And Stateful service:
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();
}
}
...........
}
Upvotes: 2