Documentation
Documentation copied to clipboard
Add example about parallel processing of work in the context of scoped dependencies
Scattered through the documentation there is advise about running parallel operations and wrapping operations in scopes. That documentation is a bit abstract and theoretical, It misses some simple examples. The lifestyles page seems like a good place to add this information.
Here's an example of the code I use to run parallel jobs in a console app.
internal static class Program
{
private static readonly Container Container;
private static readonly Type[] Jobs = { typeof(Job1), typeof(Job2) };
private static readonly Func<Container, Type, Task> JobFactory = async (container, type) =>
{
using (AsyncScopedLifestyle.BeginScope(container: Container))
{
var job = (IAmAJob) container.GetInstance(type);
await job.ProcessAsync();
}
};
static Program()
{
Container = new Container();
Container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
Container.Register<Job1>(Lifestyle.Scoped);
Container.Register<Job2>(Lifestyle.Scoped);
Container.Verify();
}
private static async Task Main()
{
var jobs = Jobs
.Select(type => Task.Run(() => JobFactory(Container, type)))
.ToArray();
await Task.WhenAll(jobs);
Console.ReadLine();
}
}
The job factory delegate ensures that each job is created in the context of the scope. Awaiting the result before returning ensures the calls value is returned before any disposable dependencies are disposed.