Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example about parallel processing of work in the context of scoped dependencies #108

Open
dotnetjunkie opened this issue Dec 11, 2019 · 1 comment

Comments

@dotnetjunkie
Copy link
Collaborator

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.

@stevenrobertsvortextanalytics
Copy link

stevenrobertsvortextanalytics commented Dec 13, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants