How to work with Parallel using the Ninject library

Asked

Viewed 62 times

2

How can you configure ninject to provide an instance of a given object for each thread that calls it?

The ninject kernel can be run before a code with parallelism or it is necessary to instantiate a new kernel within the thread code?

When executing the code below, I get open existing datareader error.

var kernel = new StandardKernel(new FooModule(), BarModule());

Parallel.ForEach(entidades, new ParallelOptions { MaxDegreeOfParallelism = 10 }, (entidade) =>
{
    //Algum código aqui
    kernel.Get<IService>().Consultar(entidade);
}

When placing the kernel creation in the thread, I do not get the open datareader error but identify that Ninject is not giving Dispose to the database connections when the thread is finished.

Parallel.ForEach(entidades, new ParallelOptions { MaxDegreeOfParallelism = 10 }, (entidade) =>
{
    var kernel = new StandardKernel(new FooModule(), BarModule());
    kernel.Get<IService>().Consultar(entidade);
}

Additional information: Time limit expired. The time period limit was reached before a pool connection was obtained. This may have occurred because all pool connections were in use and the Maximum pool size reached.

1 answer

0

Ninject will only try to do the Dispose of your object if you set its Scope. In your case I believe that the proper Scope is Inthreadscope.

Bind<IService>().To<MyService>().InThreadScope();
  • Vinicius, I tried to define this scope for the service but the exception continued to be raised as if the same instance was being used for different threads.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.