Ninject caches entered DataContext? Lifecycle management?

A series of very strange bugs has been released in my repositories. A row was not found or changed, 1 of 2 updates failed ... Nothing made sense.

As if my copy of the DataContext was cached ... Nothing made sense, and I was looking at the course of my career.

Then I noticed that the DataContext instance was passed when using dependency injection using Ninject (this is the first time I used DI ...). I thwarted the injection of addictions, and everything returned to normal. Instantly.

So dependency injection was a problem, but I still don't know why. I assume that Ninject cached the entered DataContext.

It is right?

Edit:

The binding to Ninject is as follows:

Bind<IPupilBlockService>().To<SqlPupilBlockService>()
   .WithConstructorArgument("db", new dbDataContext());
+5
3

, (, , IDisposable) , , factory, . , :

public interface IDbDataContextFactory
{
    dbDataContext CreateNew();
}

:

public class SqlPupilBlockService
{
    private IDbDataContextFactory contextFactory;

    public SqlPupilBlockService(
        IDbDataContextFactory contextFactory)
    {
        this.contextFactory = contextFactory;
    }

    public void DoSomeOperation()
    {
        using (var db = this.contextFactory.CreateNew())
        {
           // use the dbDataContext here.
        }
    }
}

, :

public class DbDataContextFactory : IDbDataContextFactory
{
    public dbDataContext CreateNew()
    {
        return new dbDataContext();
    }
}

:

Bind<IDbDataContextFactory>().To<DbDataContextFactory>();

factory , . .

UPDATE

, . , , (-). ; , , : . , .

+14

@Steven , Ninject , : InRequestScope.

Bind<IPupilBlockService>()
   .To<SqlPupilBlockService>()
   .InRequestScope()
   .WithConstructorArgument("db", new dbDataContext());
+2

. , DataContext Singleton , .

(I'm not too familiar with ninject, but the given time range is the default value, I would expect that somewhere in your application code the DataContext is explicitly defined as having a non-transition area)

+1
source

All Articles