Autofac ThreadSafe Resolve by Metadata Property Name

Viewed 95

Using Autofac Dependency injection I'm attempting to resolve a service inside of a parallel operation and keep it thread safe. I'm using the following example code below:

public class ThreadCreator
{
  private ILifetimeScope _parentScope;

  public ThreadCreator(ILifetimeScope parentScope)
  {
    this._parentScope = parentScope;
  }

  public void ThreadStart()
  {
    using (var threadLifetime = this._parentScope.BeginLifetimeScope())
    {
      var thisThreadsInstance = threadLifetime.Resolve<MyThreadScopedComponent>();
    }
  }
}

My current (non thread safe code) looks like this:

    public class ReportService : IReportService
    {
        private readonly IEnumerable<Lazy<IReportGeneratorService, IReportGeneratorMetadata>> _reportGeneratorServices;

        public ReportService(IEnumerable<Lazy<IReportGeneratorService, IReportGeneratorMetadata>> reportGeneratorServices)
        {
            _reportGeneratorServices = reportGeneratorServices;
        }

        public TestMethod(){
          //Not thread safe when called inside a Parallel.ForEach
          var reportServiceLazyLoad = _reportGeneratorServices.FirstOrDefault(s => s.Metadata.Name == myMetaDataName);
        }
     }

How can i resolve using metadata name property class in a thread safe manner? I can't figure out how utilize the threadLifeTime variable to resolve an instance of a service by MetaData.Name property filtering in a manner that is limited to the specific thread, basically converting the second block of code into the first block where its threadsafe.

Thank you!!

1 Answers

You may substitute IEnumerable for ConcurrentBag, this will guarantees a thread safe execution into collection/array level. But if you want to propagate de execution of all scope with alias or named thread, the best alternative is put the code invoke execution into one Mutex. With Mutex, you can define a name of thread and guarantees the thread safe control out of application domain, in other word, in operational system level

Related