Search code examples
asp.net-web-apiasp.net-web-api2azure-service-fabric

WebApi controller accessing its StatelessService instance


I am hosting WebApi controller inside a stateless service with one instance. The service instance (I mean the instance of the WebApiService class created by the SF runtime) maintains some transient state as member fields, exposing the state through internal (thread-safe) methods. The WebApi controller needs to call the methods to access that state.

WebApiService.cs:
-----------------
internal sealed class WebApiService : StatelessService
{
  private int _state;

  internal int GetState() { return this._state; }

ServiceController.cs:
---------------------
public class ServiceController : ApiController
{
  public async Task<IHttpActionResult> GetStateAsync()
  {
    // Here I'd like to grab somehow the WebApiService instance 
    // and call its GetState internal method.

My questions are:

  1. How can the controller get a reference to the WebApiService instance?

  2. Is it safe to store the WebApiService instance in a static field (perhaps set in the WebAspiService constructor)?


Solution

  • Inject the service instance as a dependency to your controllers through a DI container.

    Here's an example with Web API hosted on Katana using Unity. It's a stateful service but it works exactly the same way for a stateless service: https://github.com/Azure-Samples/service-fabric-dotnet-getting-started/tree/master/Services/WordCount/WordCount.Service

    Here's an example using Asp.Net Core and its built-in dependency injection container (also stateful, but same thing applies): https://github.com/vturecek/service-fabric-xray/tree/master/src/xray.Data