[英]How to use autofac inside a parallel.foreach loop
Trying to change a foreach statement to a parallel.foreach.试图将 foreach 语句更改为 parallel.foreach。 with autofac.与 autofac。
My solution is a webforms site that I am trying to add AutoFac to.我的解决方案是我试图将 AutoFac 添加到的网络表单站点。 The class that I am having a problem with is working with Autofac, with a standard foreach.我遇到问题的课程是使用标准 foreach 的 Autofac。 I would like to transition to a Parrallel.foreach.我想过渡到 Parrallel.foreach。 All the examples show a container.BeginLIfetimeScope() but no information on what container is or how to new one up.所有示例都显示了一个 container.BeginLIfetimeScope() 但没有关于容器是什么或如何新建一个的信息。
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.使用 WebForms,你可能最好使用它的特定集成: Autofac WebForms ,还有其他关于线程安全的最佳实践问题,为你生成的每个项目生成新的范围等。但以上应该足以开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.