Skip to content

Instantly share code, notes, and snippets.

@optiks
Created November 7, 2018 09:52
Show Gist options
  • Save optiks/482f5c9a6f1dc56d58d1ea8a86c9b925 to your computer and use it in GitHub Desktop.
Save optiks/482f5c9a6f1dc56d58d1ea8a86c9b925 to your computer and use it in GitHub Desktop.
// 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