title: System.Runtime.InteropServices.COMException while using service fabric
body: <p>I am creating an application in Azure Service Fabric Web API and I am facing the following issue:</p>
  
  <p>Exception:</p>
  
  <pre><code>System.Runtime.InteropServices.COMException occurred
    ErrorCode=-2146233628
    HResult=-2146233628
    Message=Field of ByRef type. (Exception from HRESULT: 0x801312E4)
    Source=mscorlib
    StackTrace:
         at System.Reflection.Emit.TypeBuilder.TermCreateClass(RuntimeModule module, Int32 tk, ObjectHandleOnStack type)
         at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
         at System.Reflection.Emit.TypeBuilder.CreateTypeInfo()
         at Microsoft.ServiceFabric.Services.Remoting.Builder.MethodBodyTypesBuilder.BuildRequestBodyType(ICodeBuilderNames codeBuilderNames, CodeBuilderContext context, MethodDescription methodDescription)
         at Microsoft.ServiceFabric.Services.Remoting.Builder.MethodBodyTypesBuilder.Build(ICodeBuilderNames codeBuilderNames, CodeBuilderContext context, MethodDescription methodDescription)
         at Microsoft.ServiceFabric.Services.Remoting.Builder.MethodBodyTypesBuilder.Build(InterfaceDescription interfaceDescription)
         at Microsoft.ServiceFabric.Services.Remoting.Builder.CodeBuilder.Microsoft.ServiceFabric.Services.Remoting.Builder.ICodeBuilder.GetOrBuildMethodBodyTypes(Type interfaceType)
         at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
         at Microsoft.ServiceFabric.Services.Remoting.Builder.ProxyGeneratorBuilder`2.Build(Type proxyInterfaceType, IEnumerable`1 interfaceDescriptions)
         at Microsoft.ServiceFabric.Services.Remoting.Builder.CodeBuilder.Microsoft.ServiceFabric.Services.Remoting.Builder.ICodeBuilder.GetOrBuildProxyGenerator(Type interfaceType)
         at Microsoft.ServiceFabric.Services.Remoting.Builder.ServiceCodeBuilder.GetOrCreateProxyGenerator(Type serviceInterfaceType)
         at Microsoft.ServiceFabric.Services.Remoting.Client.ServiceProxyFactory.CreateServiceProxy[TServiceInterface](Uri serviceUri, ServicePartitionKey partitionKey, TargetReplicaSelector targetReplicaSelector, String listenerName)
         at Microsoft.ServiceFabric.Services.Remoting.Client.ServiceProxy.Create[TServiceInterface](Uri serviceUri, ServicePartitionKey partitionKey, TargetReplicaSelector targetReplicaSelector, String listenerName)
         at WebService.Controllers.HomeController.&lt;GetAsync&gt;d__0.MoveNext() in C:\Users\shkulka\Documents\Visual Studio 2015\Projects\SortingApp\WebService\Controllers\HomeController.cs:line 17
    InnerException: 
  </code></pre>
  
  <p>Line at which exception occurs: </p>
  
  <pre><code>    IRequestManagerService proxy = ServiceProxy.Create&lt;IRequestManagerService&gt;(new Uri("fabric:/SortingApp/RequestManagerService"));
  </code></pre>
  
  <p>Some code for reference:</p>
  
  <pre><code>namespace WebService.Controllers
  {
      [Route("api/[controller]")]
      public class HomeController : Controller 
      {
          [HttpGet]
          public async Task&lt;IActionResult&gt; GetAsync(int opId, string sortType = "Quick", string guid="454", string commaSeperatedArray="1,2,3,4")
          {
              IRequestManagerService proxy = ServiceProxy.Create&lt;IRequestManagerService&gt;(new Uri("fabric:/SortingApp/RequestManagerService"));
             //rest of the code continues . . . 
  </code></pre>
  
  <p>Exception occurs when I hit the following URL:</p>
  
  <pre><code>http://localhost:8792/api/home?opId=0&amp;sortType=Quick&amp;guid=12&amp;commaSeperatedArray=1,2,3,4
  </code></pre>
  
  <p>I am running my project with admin privileges. Platform target is x64 throughout the solution. </p>
  
  <p>How do I get rid of the exception?</p>
  
  <hr>
  
  <p>Update 1:</p>
  
  <p>Before I hit the URL, I can observe the following regarding service fabric.</p>
  
  <p>In service fabric explorer:</p>
  
  <p><a href="https://i.stack.imgur.com/v4jTU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v4jTU.png" alt="enter image description here"></a></p>
  
  <p>In Diagnostic Events window:</p>
  
  <pre><code>    {
    "Timestamp": "2017-09-06T10:49:34.7442479+05:30",
    "ProviderName": "Microsoft-ServiceFabric-Services",
    "Id": 2,
    "Message": "RunAsync has been cancelled for a stateful service replica.  The cancellation will be considered 'slow' if RunAsync does not halt execution within 4000 milliseconds.  Application Type Name: GettingStartedApplicationType, Application Name: fabric:/GettingStartedApplication, Service Type Name: MyActorServiceType, Service Name: fabric:/GettingStartedApplication/MyActorService, Partition Id: 097c837b-857e-4f10-8c3a-8a902c1f0bb6, Replica Id: 131491461074099453",
    "ProcessId": 34840,
    "Level": "Informational",
    "Keywords": "0x0000F00000000000",
    "EventName": "StatefulRunAsyncCancellation",
    "ActivityID": null,
    "RelatedActivityID": null,
    "Payload": {
      "applicationTypeName": "GettingStartedApplicationType",
      "applicationName": "fabric:/GettingStartedApplication",
      "serviceTypeName": "MyActorServiceType",
      "serviceName": "fabric:/GettingStartedApplication/MyActorService",
      "partitionId": "097c837b-857e-4f10-8c3a-8a902c1f0bb6",
      "replicaId": 131491461074099453,
      "slowCancellationTimeMillis": 4000.0
    }
  }
  
  {
    "Timestamp": "2017-09-06T10:49:34.760793+05:30",
    "ProviderName": "Microsoft-ServiceFabric-Services",
    "Id": 2,
    "Message": "RunAsync has been cancelled for a stateful service replica.  The cancellation will be considered 'slow' if RunAsync does not halt execution within 4000 milliseconds.  Application Type Name: GettingStartedApplicationType, Application Name: fabric:/GettingStartedApplication, Service Type Name: MyActorServiceType, Service Name: fabric:/GettingStartedApplication/MyActorService, Partition Id: 78f9a969-4f09-4d8b-932f-4962cce7f4cd, Replica Id: 131491461074094464",
    "ProcessId": 27832,
    "Level": "Informational",
    "Keywords": "0x0000F00000000000",
    "EventName": "StatefulRunAsyncCancellation",
    "ActivityID": null,
    "RelatedActivityID": null,
    "Payload": {
      "applicationTypeName": "GettingStartedApplicationType",
      "applicationName": "fabric:/GettingStartedApplication",
      "serviceTypeName": "MyActorServiceType",
      "serviceName": "fabric:/GettingStartedApplication/MyActorService",
      "partitionId": "78f9a969-4f09-4d8b-932f-4962cce7f4cd",
      "replicaId": 131491461074094464,
      "slowCancellationTimeMillis": 4000.0
    }
  }
  </code></pre>
  
  <p>After hitting URL:</p>
  
  <p><a href="https://i.stack.imgur.com/Qia8H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qia8H.png" alt="enter image description here"></a></p>
  
  <hr>
  
  <p>Update 2:</p>
  
  <p>Interface:</p>
  
  <pre><code>namespace RequestManagerService.Interfaces
  {
      public interface IRequestManagerService : IService
      {
          Task submitSortRequest(string sortType, string guid, string commaSeperatedArray);
          Task&lt;bool&gt; isSortingComplete(string guid);
          Task&lt;string&gt; getSortedArray(string guid);
          Task&lt;bool&gt; isSortRequested(string sortType, ref string commaSeperatedArray, ref string guid);
          Task setSortResult(string sortType, string guid, string sortedArray);
      }
  }
  </code></pre>
  
  <p>Interface implementation:</p>
  
  <pre><code>namespace RequestManagerService
  {
      /// &lt;summary&gt;
      /// An instance of this class is created for each service instance by the Service Fabric runtime.
      /// &lt;/summary&gt;
      internal sealed class RequestManagerService : StatelessService, IRequestManagerService
      {
          // &lt;guid,&lt;sorttype, array, isSortComplete&gt;&gt;
          Dictionary&lt;string, Tuple&lt;string, string, bool&gt;&gt; SortDictionary = new Dictionary&lt;string, Tuple&lt;string, string, bool&gt;&gt;(); 
          public RequestManagerService(StatelessServiceContext context)
              : base(context)
          {
  
          }
  
          public async Task&lt;string&gt; getSortedArray(string guid)
          {
              Tuple&lt;string, string, bool&gt; tempTuple;
              string sortedArray= "";
  
              if (await isSortingComplete(guid))
              {
                  SortDictionary.TryGetValue(guid, out tempTuple);
                  sortedArray = tempTuple.Item2;
              }
              else
              {
                  sortedArray = "Either there no request with this guid or the sorting is not yet complete.";
              }
              return sortedArray;
          }
  
          public Task&lt;bool&gt; isSortingComplete(string guid)
          {
              bool isSortComplete = false;
              Tuple&lt;string, string, bool&gt; tempTuple;
  
              if (SortDictionary.ContainsKey(guid)) {
                  SortDictionary.TryGetValue(guid, out tempTuple);
                  isSortComplete = tempTuple.Item3;
              }
  
              return Task.FromResult(isSortComplete);
          }
  
          public Task&lt;bool&gt; isSortRequested(string sortType, ref string commaSeperatedArray, ref string guid)
          {
              bool requestFound = false;
  
              foreach(KeyValuePair&lt;string, Tuple&lt;string, string, bool&gt;&gt; entry in SortDictionary)
              {
                  if (entry.Value.Item1 == sortType &amp;&amp; entry.Value.Item3 == false)
                  {
                      commaSeperatedArray = entry.Value.Item2;
                      guid = entry.Key;
                      requestFound = true;
                      break;
                  }
              }
  
              return Task.FromResult(requestFound);
          }
  
          public Task setSortResult(string sortType, string guid, string sortedArray)
          {
              if (SortDictionary.ContainsKey(guid))
              {
                  Tuple&lt;string, string, bool&gt; updatedTuple = new Tuple&lt;string, string, bool&gt;(sortType, sortedArray, true);
                  SortDictionary[guid] = updatedTuple;
              }
              return Task.FromResult&lt;object&gt;(null);
          }
  
          public Task submitSortRequest(string sortType, string guid, string commaSeperatedArray)
          {
              Tuple&lt;string, string, bool&gt; tuple = new Tuple&lt;string, string, bool&gt;(sortType, commaSeperatedArray, false);
              SortDictionary.Add(guid, tuple);
              return Task.FromResult&lt;object&gt;(null);
          }
  
          /// &lt;summary&gt;
          /// Optional override to create listeners (e.g., TCP, HTTP) for this service replica to handle client or user requests.
          /// &lt;/summary&gt;
          /// &lt;returns&gt;A collection of listeners.&lt;/returns&gt;
          protected override IEnumerable&lt;ServiceInstanceListener&gt; CreateServiceInstanceListeners()
          {
              return new ServiceInstanceListener[1] {
                  new ServiceInstanceListener(this.CreateServiceRemotingListener)
              };
          }
  
          /// &lt;summary&gt;
          /// This is the main entry point for your service instance.
          /// &lt;/summary&gt;
          /// &lt;param name="cancellationToken"&gt;Canceled when Service Fabric needs to shut down this service instance.&lt;/param&gt;
          protected override async Task RunAsync(CancellationToken cancellationToken)
          {
              // TODO: Replace the following sample code with your own logic 
              //       or remove this RunAsync override if it's not needed in your service.
  
              long iterations = 0;
  
              while (true)
              {
                  cancellationToken.ThrowIfCancellationRequested();
  
                  ServiceEventSource.Current.ServiceMessage(this.Context, "Working-{0}", ++iterations);
  
                  await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
              }
          }
      }
  }
  </code></pre>