title: How to add thread lock to a transient service
body: <p>I am using Mediator in .Net Core 5 and want to add a lock while processing a task.</p>
  <p>I have used the below codes, but it does not work as the Mediator handlers are not Singleton services.</p>
  <pre><code>public class MyCommandHandler : IRequestHandler&lt;MyCommand, bool&gt;
  {
    private object thisLock = new();
    private readonly IService _service;
  
    public MyCommandHandler(IService service)
    {
        _service = service;
    }
  
    public async Task&lt;bool&gt; Handle(MyCommand request, CancellationToken cancellationToken)
    {
       var items = _service.Get().Result;
       lock (thisLock)
       {
          //Some work
          await _service.Add(new Foo{ Id = 1 });   
       }
    }
  }
  </code></pre>
  <p>In my Startup</p>
  <pre><code>services.AddMediatR(Assembly.GetExecutingAssembly());
  services.AddSingleton&lt;IService , MyService &gt;();
  </code></pre>
  <p>Is there a way I can fix this locking?</p>
  <p>I have tried to register the handler as a Singleton service but it gave me a run time error</p>
  <pre><code>services.AddSingleton(typeof(IRequestHandler&lt;,&gt;), typeof(IRequestHandler&lt;MyCommand, bool&gt;));
  </code></pre>