简体   繁体   中英

How to use autofac inside a parallel.foreach loop

Trying to change a foreach statement to a parallel.foreach. with autofac.

My solution is a webforms site that I am trying to add AutoFac to. The class that I am having a problem with is working with Autofac, with a standard foreach. I would like to transition to a Parrallel.foreach. All the examples show a container.BeginLIfetimeScope() but no information on what container is or how to new one up.

Parallel.ForEach(items, item =>
{
     // Note I'm calling container.BeginLifetimeScope() inside the ForEach
     using (var parallelScope = container.BeginLifetimeScope())
     {
         var aDataService = parallelScope.Resolve<IaDataService>();
         aDataService.SomeProcessing();
     }
 }

The code below compiles and works for me. Given:

public interface IaDataService
{
    void SomeProcessing(object obj);
}

public class DataService : IaDataService
{
    public void SomeProcessing(object obj)
    {

    }
}

We could do something like:

var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<DataService>()
    .As<IaDataService>();
var container = containerBuilder.Build();

var items = new List<object>{"abc", 123};
Parallel.ForEach(items, item =>
{
    // Note I'm calling container.BeginLifetimeScope() inside the ForEach
    using (var parallelScope = container.BeginLifetimeScope())
    {
        var aDataService = parallelScope.Resolve<IaDataService>();
        aDataService.SomeProcessing(item);
    }
});

Using WebForms, you're likely better off using the specific integration for it: Autofac WebForms , and there are other best practice questions about thread safety, generating new scopes for each item you generate etc. But the above should be enough to get started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM