title: An error occurred when trying to create a controller of type 'xxx'. Make sure that the controller has a parameterless public constructor. Ninject
body: <p>I am working in .Net framework 4.7.2. I am facing a problem while using NInject dependency injection resolver. I am getting the following error when trying to access NotificationController, which has no parameterless constructor:</p>
  <pre><code>&quot;Message&quot;: &quot;An error has occurred.&quot;,
      &quot;ExceptionMessage&quot;: &quot;An error occurred when trying to create a controller of type 'NotificationController'. Make sure that the controller has a parameterless public constructor.&quot;,
      &quot;ExceptionType&quot;: &quot;System.InvalidOperationException&quot;,
      &quot;StackTrace&quot;: &quot;   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.&lt;SendAsync&gt;d__15.MoveNext()&quot;,
      &quot;InnerException&quot;: {
          &quot;Message&quot;: &quot;An error has occurred.&quot;,
          &quot;ExceptionMessage&quot;: &quot;Type 'ABC.API.Controllers.NotificationController' does not have a default constructor&quot;,
          &quot;ExceptionType&quot;: &quot;System.ArgumentException&quot;,
          &quot;StackTrace&quot;: &quot;   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1&amp; activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)&quot;
  </code></pre>
  <p>Here is my complete code:</p>
  <p>INotificationService:</p>
  <pre><code>using System.Threading;
  using System.Threading.Tasks;
  using ABC.API.Models;
  
  namespace ABC.API.Services
  {
      public interface INotificationService
      {
          Task&lt;bool&gt; CreateOrUpdateInstallationAsync(DeviceInstallation deviceInstallation, CancellationToken token);
          Task&lt;bool&gt; DeleteInstallationByIdAsync(string installationId, CancellationToken token);
          Task&lt;bool&gt; RequestNotificationAsync(NotificationRequest notificationRequest, CancellationToken token);
      }
  }
  </code></pre>
  <p>NotificationHubService implementing INotificationService:</p>
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading;
  using System.Threading.Tasks;
  using Microsoft.Azure.NotificationHubs;
  using Microsoft.Extensions.Logging;
  using Microsoft.Extensions.Options;
  using ABC.API.Models;
  
  namespace ABC.API.Services
  {
      public class NotificationHubService : INotificationService
      {
          readonly NotificationHubClient _hub;
          readonly Dictionary&lt;string, NotificationPlatform&gt; _installationPlatform;
          readonly ILogger&lt;NotificationHubService&gt; _logger;
  
          public NotificationHubService(IOptions&lt;NotificationHubOptions&gt; options, ILogger&lt;NotificationHubService&gt; logger)
          {
              _logger = logger;
              _hub = NotificationHubClient.CreateClientFromConnectionString(
                  options.Value.ConnectionString,
                  options.Value.Name);
  
              _installationPlatform = new Dictionary&lt;string, NotificationPlatform&gt;
              {
                  { nameof(NotificationPlatform.Apns).ToLower(), NotificationPlatform.Apns },
                  { nameof(NotificationPlatform.Fcm).ToLower(), NotificationPlatform.Fcm }
              };
          }
  
          public async Task&lt;bool&gt; CreateOrUpdateInstallationAsync(DeviceInstallation deviceInstallation, CancellationToken token)
          {
              if (string.IsNullOrWhiteSpace(deviceInstallation?.InstallationId) ||
                  string.IsNullOrWhiteSpace(deviceInstallation?.Platform) ||
                  string.IsNullOrWhiteSpace(deviceInstallation?.PushChannel))
                  return false;
  
              var installation = new Installation()
              {
                  InstallationId = deviceInstallation.InstallationId,
                  PushChannel = deviceInstallation.PushChannel,
                  Tags = deviceInstallation.Tags
              };
  
              if (_installationPlatform.TryGetValue(deviceInstallation.Platform, out var platform))
                  installation.Platform = platform;
              else
                  return false;
  
              try
              {
                  await _hub.CreateOrUpdateInstallationAsync(installation, token);
              }
              catch
              {
                  return false;
              }
  
              return true;
          }
  
          public async Task&lt;bool&gt; DeleteInstallationByIdAsync(string installationId, CancellationToken token)
          {
              if (string.IsNullOrWhiteSpace(installationId))
                  return false;
  
              try
              {
                  await _hub.DeleteInstallationAsync(installationId, token);
              }
              catch
              {
                  return false;
              }
  
              return true;
          }
  
          public async Task&lt;bool&gt; RequestNotificationAsync(NotificationRequest notificationRequest, CancellationToken token)
          {
              if ((notificationRequest.Silent &amp;&amp;
                  string.IsNullOrWhiteSpace(notificationRequest?.Action)) ||
                  (!notificationRequest.Silent &amp;&amp;
                  (string.IsNullOrWhiteSpace(notificationRequest?.Text)) ||
                  string.IsNullOrWhiteSpace(notificationRequest?.Action)))
                  return false;
  
              var androidPushTemplate = notificationRequest.Silent ?
                  PushTemplates.Silent.Android :
                  PushTemplates.Generic.Android;
  
              var iOSPushTemplate = notificationRequest.Silent ?
                  PushTemplates.Silent.iOS :
                  PushTemplates.Generic.iOS;
  
              var androidPayload = PrepareNotificationPayload(
                  androidPushTemplate,
                  notificationRequest.Text,
                  notificationRequest.Action);
  
              var iOSPayload = PrepareNotificationPayload(
                  iOSPushTemplate,
                  notificationRequest.Text,
                  notificationRequest.Action);
  
              try
              {
                  if (notificationRequest.Tags.Length == 0)
                  {
                      // This will broadcast to all users registered in the notification hub
                      await SendPlatformNotificationsAsync(androidPayload, iOSPayload, token);
                  }
                  else if (notificationRequest.Tags.Length &lt;= 20)
                  {
                      await SendPlatformNotificationsAsync(androidPayload, iOSPayload, notificationRequest.Tags, token);
                  }
                  else
                  {
                      var notificationTasks = notificationRequest.Tags
                          .Select((value, index) =&gt; (value, index))
                          .GroupBy(g =&gt; g.index / 20, i =&gt; i.value)
                          .Select(tags =&gt; SendPlatformNotificationsAsync(androidPayload, iOSPayload, tags, token));
  
                      await Task.WhenAll(notificationTasks);
                  }
  
                  return true;
              }
              catch (Exception e)
              {
                  _logger.LogError(e, &quot;Unexpected error sending notification&quot;);
                  return false;
              }
          }
  
          string PrepareNotificationPayload(string template, string text, string action) =&gt; template
              .Replace(&quot;$(alertMessage)&quot;, text)
              .Replace(&quot;$(alertAction)&quot;, action);
  
          Task SendPlatformNotificationsAsync(string androidPayload, string iOSPayload, CancellationToken token)
          {
              var sendTasks = new Task[]
              {
                  _hub.SendFcmNativeNotificationAsync(androidPayload, token),
                  _hub.SendAppleNativeNotificationAsync(iOSPayload, token)
              };
  
              return Task.WhenAll(sendTasks);
          }
  
          Task SendPlatformNotificationsAsync(string androidPayload, string iOSPayload, IEnumerable&lt;string&gt; tags, CancellationToken token)
          {
              var sendTasks = new Task[]
              {
                  _hub.SendFcmNativeNotificationAsync(androidPayload, tags, token),
                  _hub.SendAppleNativeNotificationAsync(iOSPayload, tags, token)
              };
  
              return Task.WhenAll(sendTasks);
          }
      }
  }
  </code></pre>
  <p>NotificationController which contains INotificationService parameter in constructure</p>
  <pre><code>using ABC.API.Models;
  using ABC.API.Services;
  using System;
  using System.Collections.Generic;
  using System.ComponentModel.DataAnnotations;
  using System.Linq;
  using System.Net;
  using System.Net.Http;
  using System.Threading;
  using System.Threading.Tasks;
  using System.Web;
  using System.Web.Http;
  
  namespace ABC.API.Controllers
  {
      public class NotificationController : ApiController
      {
          readonly INotificationService _notificationService;
  
          public NotificationController(INotificationService notificationService)
          {
              _notificationService = notificationService;
          }
  
          [HttpPut]
          [Route(&quot;installations&quot;)]
          //[ProducesResponseType((int)HttpStatusCode.OK)]
          //[ProducesResponseType((int)HttpStatusCode.BadRequest)]
          //[ProducesResponseType((int)HttpStatusCode.UnprocessableEntity)]
          public async Task&lt;IHttpActionResult&gt; UpdateInstallation(
              [Required] DeviceInstallation deviceInstallation)
          {
              var success = await _notificationService
                  .CreateOrUpdateInstallationAsync(deviceInstallation, HttpContext.Current.Request.TimedOutToken);
  
              if (!success)
                  return NotFound();
  
              return Ok();
          }
  
          [HttpDelete()]
          [Route(&quot;installations/{installationId}&quot;)]
          //[ProducesResponseType((int)HttpStatusCode.OK)]
          //[ProducesResponseType((int)HttpStatusCode.BadRequest)]
          //[ProducesResponseType((int)HttpStatusCode.UnprocessableEntity)]
          public async Task&lt;IHttpActionResult&gt; DeleteInstallation(
              [Required][FromBody] string installationId)
          {
              // Probably want to ensure deletion even if the connection is broken
              var success = await _notificationService
                  .DeleteInstallationByIdAsync(installationId, CancellationToken.None);
  
              if (!success)
                  return NotFound();
  
              return Ok();
          }
  
          [HttpPost]
          [Route(&quot;requests&quot;)]
          //[ProducesResponseType((int)HttpStatusCode.OK)]
          //[ProducesResponseType((int)HttpStatusCode.BadRequest)]
          //[ProducesResponseType((int)HttpStatusCode.UnprocessableEntity)]
          public async Task&lt;IHttpActionResult&gt; RequestPush(
              [Required] NotificationRequest notificationRequest)
          {
              if ((notificationRequest.Silent &amp;&amp;
                  string.IsNullOrWhiteSpace(notificationRequest?.Action)) ||
                  (!notificationRequest.Silent &amp;&amp;
                  string.IsNullOrWhiteSpace(notificationRequest?.Text)))
                  return BadRequest();
  
              var success = await _notificationService
                  .RequestNotificationAsync(notificationRequest, HttpContext.Current.Request.TimedOutToken);
  
              if (!success)
                  return NotFound();
  
              return Ok();
          }
      }
  }
  
  </code></pre>
  <p>And here is NotificationHubOptions which is declared as constructor parameter in NotificationHubService.</p>
  <pre><code>using System.ComponentModel.DataAnnotations;
  
  namespace ABC.API.Models
  {
      public class NotificationHubOptions
      {
          [Required]
          public string Name { get; set; }
  
          [Required]
          public string ConnectionString { get; set; }
      }
  }
  </code></pre>
  <p>And then I am doing this using NInject library:</p>
  <pre><code>/// &lt;summary&gt;
          /// Load your modules or register your services here!
          /// &lt;/summary&gt;
          /// &lt;param name=&quot;kernel&quot;&gt;The kernel.&lt;/param&gt;
          private static void RegisterServices(IKernel kernel)
          {
              NotificationHubOptions options = new NotificationHubOptions();
              options.ConnectionString = ConfigurationManager.AppSettings[&quot;DefaultFullSharedAccessSignature&quot;].ToString();
              options.Name = ConfigurationManager.AppSettings[&quot;NotificationHubName&quot;].ToString();
  
              kernel.Bind&lt;INotificationService&gt;().To&lt;NotificationHubService&gt;().InSingletonScope()
                  .WithConstructorArgument&lt;NotificationHubOptions&gt;(options);
          }
  </code></pre>
  <p>I had followed these links <a href="https://www.dotnettricks.com/learn/webapi/dependency-interjection-in-aspnet-web-api" rel="nofollow noreferrer">https://www.dotnettricks.com/learn/webapi/dependency-interjection-in-aspnet-web-api</a> and <a href="https://github.com/ninject/Ninject/issues/270" rel="nofollow noreferrer">https://github.com/ninject/Ninject/issues/270</a> for NIjnect. For Push Notification Service, I followed this article <a href="https://docs.microsoft.com/en-us/azure/developer/mobile-apps/notification-hubs-backend-service-xamarin-forms#authenticate-clients-using-an-api-key-optional" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/developer/mobile-apps/notification-hubs-backend-service-xamarin-forms#authenticate-clients-using-an-api-key-optional</a>. In Push notification article, they had used .Net core and they had injected the dependency through ConfigureService as below:</p>
  <pre><code>services.AddSingleton&lt;INotificationService, NotificationHubService&gt;();
              services.AddOptions&lt;NotificationHubOptions&gt;()
                  .Configure(Configuration.GetSection(&quot;NotificationHub&quot;).Bind)
                  .ValidateDataAnnotations();
  
  </code></pre>
  <p>I could not understand what I am missing. Please also suggest how to inject ILogger to NotificationHubService constructor.</p>