Service Fabric is a great tool for implementing Microservices pattern and ASP.NET MVC is a great framework for websites. How to connect these two? There are different ways you can remotely call a service from Service Fabric. In this blog, I’ll explore one of them.

This blog is using the sample that is covered in my other blog:Is Service Fabric slow for development? There’s a way to make it faster.

The full code for it is in this Git repository:

To expose the service is pretty easy. All you need is to add a reference to these packages and to override one method:

<package id="Microsoft.ServiceFabric.Services.Remoting" version="2.8.211" targetFramework="net461" />
<package id="Microsoft.ServiceFabric.FabricTransport.Internal" version="2.8.211" targetFramework="net461" />
protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners()
	return new[] { new ServiceReplicaListener(context => this.CreateServiceRemotingListener(context)) };

In the website project there is a little bit more setup, but after that, it’s pretty simple.

  1. Add helper classes for MVC
    • UsersStateServiceExtensions – This class is used to simplify adding the service in the Startup class. All you need is adding this code to the ConfigureServices method:


      public static class UsersStateServiceExtensions
          public static IServiceCollection AddUsersStateService(this IServiceCollection services)
              if (services == null)
                 throw new ArgumentNullException(nameof(services));
              #if STANDALONE
              //Register standalone services
                          context => new UsersStateService.UsersStateService(context)).GetAwaiter().GetResult();
              return services.AddSingleton<IUsersStateService, ServiceFabricUsersStateService>();
    • ServiceFabricUsersStateService – This class implements the proxy pattern, and it ensures creating a new service instance per each request.
  2. Update the Controllers
    • Use dependency injection to get a reference to the UsersStateService:
      private readonly IUsersStateService userStateService;
      public HomeController(IUsersStateService userStateService)
      	this.userStateService = userStateService;
    • Send the current state to the view and update the state:
      public async Task<IActionResult> Index()
      	ViewData["State"] = await userStateService.GetUserStateAsync();
      	await userStateService.SetUserStateAsync("Last visited page was Index");
      	return View();
    • Update the views to show the state:
      <p>State: @ViewData["State"] </p>

Let me know if you have any questions or comments on how I can improve the blog and/or the source code.


Leave a Reply

Your email address will not be published. Required fields are marked *