title: Constructor Injection Only When Needed
body: <p>I am looking for a way to inject an interface into a class only when it needs to be used.</p>
  <p>For context I am trying to set up publish/subscribe messaging between two different projects, and to do this I am using both RabbitMQ and Azure Service Bus to suit different needs. To determine which one I want to use I use a boolean value which is set in app settings, like so:</p>
  <pre><code>if (AppSettingsProvider.MessagingEnabled)
  {
      if (AppSettingsProvider.AzureServiceBusEnabled)
      {
          services.AddSingleton&lt;IEventBus, EventBusServiceBus&gt;(
          sp =&gt;
          {
              var serviceBusPersistentConnection = sp.GetRequiredService&lt;IServiceBusPersistentConnection&gt;();
              var scope = sp.CreateScope();
              var logger = sp.GetRequiredService&lt;ILogger&lt;EventBusServiceBus&gt;&gt;();
              var eventBusSubcriptionsManager = sp.GetRequiredService&lt;IEventBusSubscriptionManager&gt;();
              var subscriptionClientName = AppSettingsProvider.SubscriptionName;
  
              return new EventBusServiceBus(serviceBusPersistentConnection, logger, eventBusSubcriptionsManager, subscriptionClientName, scope);
          });
      }
      else
      {
          services.AddSingleton&lt;IEventBus, EventBusRabbitMQ&gt;(
          ...
      }
  }
  </code></pre>
  <p>I have an if statement that wraps all of this checking MessagingEnabled. Ideally I don't want either implementation to be set up if messaging is turned off.</p>
  <p>My issue here is that IEventBus is injected in different event publishing classes, however if I have messaging turned off I get exceptions that there is no instantiation of the injected IEventBus. As an example:</p>
  <pre><code>public class EventBusPublisher : IEventBusPublisher
  {
      private readonly IEventBus _eventBus;
      private readonly IMapper _mapper;
  
      public EventBusPublisher(IMapper mapper, IEventBus eventBus)
      {
          _mapper = mapper;
          _eventBus = eventBus;
      }
  </code></pre>
  <p>I thought maybe if I made the IEventBus nullable it may solve this issue however it has not.</p>
  <p>This class will never be used if messaging is turned off, so there should be no problems with there not being an event bus implementation available in this case. Is there a way to, I guess tell the class its okay that there is no implementation for it?</p>
  <p>Thanks.</p>