Ninject: entity object cannot be referenced by multiple instances of IEntityChangeTracker

前端 未结 3 1263
攒了一身酷
攒了一身酷 2021-01-23 07:15

I am starting to use Ninject in my MVC5 code-first app. Here\'s my NinjectWebCommon.cs:

private static IKernel CreateKernel()
    {
        var kernel = new Stan         


        
3条回答
  •  死守一世寂寞
    2021-01-23 07:44

    This may not answer the question. But I tend to use the IDbContextFactory that EF provides you with and do something like this:

    public interface IDefaultContextFactory : IDbContextFactory {}
    
    public class DefaultContextFactory : IDefaultContextFactory 
    {
        private readonly Lazy lazyContext = new Lazy(() => new CMSContext());
    
        public CMSContext Create() 
        {
            return lazyContext.Value;
        }
    }
    

    Then you just bind that, and when you need the context you can do something like this:

    public class ExecutiveRepository : IExecutiveRepository, IDisposable
    {
        private readonly CMSContext context;
    
        public ExecutiveRepository(IDefaultContextFactory contextFactory)
        {
            this.context = contextFactory.Create();
        }
    }
    

    I believe @BatteryBackupUnit is correct, I would also consider using the above pattern for contexts.

提交回复
热议问题