Working with Parallel using the NInject library

2

How can I configure ninject to make it available to an instance of a given object for each thread that calls it?

Can the ninject kernel be run before a code with parallelism or is it necessary to instantiate a new kernel inside the thread code?

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

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 I put the kernel creation in the thread, I do not get the open datareader error but I identify that Ninject is not giving the connections to the database when the thread is terminated.

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

Additional information: Timeout expired. The time period   threshold was reached before a pool connection was obtained. That   may have occurred because all pool connections were in use and the   maximum pool size has been reached.

    
asked by anonymous 14.04.2016 / 23:26

1 answer

0

Ninject will only try to make your object available if you set its scope. In your case I believe the proper scope is the InThreadScope.

Bind<IService>().To<MyService>().InThreadScope();
    
15.04.2016 / 14:35