Skip to content

Instantly share code, notes, and snippets.

@wes-goulet
Created July 31, 2017 20:26
Show Gist options
  • Save wes-goulet/37902dfe4ccb189423a86a049cde3b48 to your computer and use it in GitHub Desktop.
Save wes-goulet/37902dfe4ccb189423a86a049cde3b48 to your computer and use it in GitHub Desktop.
/// <summary>
/// Provides a way to override the current <see cref="implementation"/>.
/// </summary>
/// <param name="valueFactory">Factory that creates the new implementation</param>
/// <param name="implementation">Reference to the current implementation, it will be
/// updated with the new <see cref="valueFactory"/>.</param>
/// <param name="lazyLoad">Set to true if you want to lazy load your new implementation
/// (not recommended if your implementation listens for events in it's constructor).</param>
public static void OverrideDefault<TInterface>(Func<TInterface> valueFactory, ref Lazy<TInterface> implementation, bool lazyLoad = false)
{
if (implementation.IsValueCreated)
{
// ReSharper disable once SuspiciousTypeConversion.Global
var oldImpl = implementation.Value as INeedToUnSubscribeFromEvents;
oldImpl?.UnSubscribeFromEvents();
}
implementation = new Lazy<TInterface>(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication);
if (!lazyLoad)
{
Current.Touch();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment