Created
November 7, 2018 09:52
-
-
Save optiks/482f5c9a6f1dc56d58d1ea8a86c9b925 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Implement this on your context | |
public interface IContextDisposedState | |
{ | |
bool IsDisposed { get; } | |
} | |
public class MyLazyLoader : ILazyLoader | |
{ | |
private readonly ILazyLoader _efCoreLazyLoader; | |
private readonly ICurrentDbContext _currentContext; | |
public HuxleyLazyLoader(ICurrentDbContext currentContext, IDiagnosticsLogger<DbLoggerCategory.Infrastructure> logger) | |
{ | |
_currentContext = currentContext; | |
_efCoreLazyLoader = new LazyLoader(currentContext, logger); | |
} | |
private bool ContextIsDisposed => ((IContextDisposedState)_currentContext.Context).IsDisposed; | |
private bool AutoDetectChangesEnabled | |
{ | |
get | |
{ | |
return _currentContext.Context.ChangeTracker.AutoDetectChangesEnabled; | |
} | |
set | |
{ | |
_currentContext.Context.ChangeTracker.AutoDetectChangesEnabled = value; | |
} | |
} | |
public void Load(object entity, [CallerMemberName] string navigationName = null) | |
{ | |
if (ContextIsDisposed) | |
return; | |
var originalChangeTrackingState = AutoDetectChangesEnabled; | |
try | |
{ | |
AutoDetectChangesEnabled = false; | |
_efCoreLazyLoader.Load(entity, navigationName); | |
} | |
finally | |
{ | |
if (originalChangeTrackingState) | |
AutoDetectChangesEnabled = true; | |
} | |
} | |
public async Task LoadAsync(object entity, CancellationToken cancellationToken = default(CancellationToken), [CallerMemberName] string navigationName = null) | |
{ | |
if (ContextIsDisposed) | |
return; | |
var originalChangeTrackingState = AutoDetectChangesEnabled; | |
try | |
{ | |
AutoDetectChangesEnabled = false; | |
await _efCoreLazyLoader.LoadAsync(entity, cancellationToken, navigationName); | |
} | |
finally | |
{ | |
if (originalChangeTrackingState) | |
AutoDetectChangesEnabled = true; | |
} | |
} | |
} | |
// Register the replacement service | |
new DbContextOptionsBuilder() | |
.ReplaceService<ILazyLoader, MyLazyLoader>(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment