Can I clone DbContext from existing one?

前端 未结 1 1141
时光说笑
时光说笑 2021-01-29 01:55

I\'m working on .NET Core Web API and I have one endpoint where I want to run three operations in parallel. All three of them use the same database, so I need three copies of Db

相关标签:
1条回答
  • 2021-01-29 02:44

    I definitely would not recommend any deepcloning for multiple reasons, one of them being that you will need to figure out a lot of EF internals to make it right, and internals can change(and you will need to spend some time on it).

    Second option would be just creating your context manually, which I would recommend against also cause modern infrastructure uses DbContext pooling.

    So what you can to register Func<DbContext> (or create your own factory) like this:

     services.AddSingleton<Func<DbContext>>(provider => () => 
            {
                var scope = provider.CreateScope();
                return scope.ServiceProvider.GetRequiredService<DbContext>();
            });    
    

    the issue here is that scope here would not be disposed and you can't(if you have default scope for your DbContext) dispose the scope inside the Func cause your context will be disposed also. So you can try creating some disposable wrapper so you can manually dispose everything like this:

        public class DisposableScopedContextWrapper : IDisposable
        {
            private readonly IServiceScope _scope;
            public DbContext Context { get; }
    
            public DisposableScopedContextWrapper(IServiceScope scope)
            {
                _scope = scope;
                Context = _scope.ServiceProvider.GetService<DbContext>();
            }
    
            public void Dispose()
            {
                _scope.Dispose();
            }
        } 
    
        services.AddSingleton<Func<DisposableScopedContextWrapper>>(provider =>() => 
            {
                var scope = provider.CreateScope();
                return new DisposableScopedContextWrapper(scope);
            });
    

    Inject in your classes Func<DisposableScopedContextWrapper> func and use it

     using (var wrapper = func())
            {
                wrapper.Context...
            }
    
    0 讨论(0)
提交回复
热议问题