Skip to content

Commit

Permalink
Implement singleton pattern for ComWrappers (#675)
Browse files Browse the repository at this point in the history
* implement singleton pattern for ComWrappersSupport
  • Loading branch information
j0shuams authored Jan 19, 2021
1 parent 913244d commit 5e14799
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions src/WinRT.Runtime/ComWrappersSupport.net5.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using WinRT.Interop;
using static System.Runtime.InteropServices.ComWrappers;
Expand All @@ -15,6 +12,20 @@ namespace WinRT
{
public static partial class ComWrappersSupport
{
// Instance field and property for Singleton pattern: ComWrappers `set` method should be idempotent
private static DefaultComWrappers _instance;
private static DefaultComWrappers DefaultComWrappersInstance
{
get
{
if (_instance == null)
{
_instance = new DefaultComWrappers();
}
return _instance;
}
}

internal static readonly ConditionalWeakTable<object, InspectableInfo> InspectableInfoTable = new ConditionalWeakTable<object, InspectableInfo>();
internal static readonly ThreadLocal<Type> CreateRCWType = new ThreadLocal<Type>();

Expand All @@ -30,8 +41,9 @@ private static ComWrappers ComWrappers
{
if (_comWrappers is null)
{
_comWrappers = new DefaultComWrappers();
ComWrappers.RegisterForTrackerSupport(_comWrappers);
var comWrappersToSet = DefaultComWrappersInstance;
ComWrappers.RegisterForTrackerSupport(comWrappersToSet);
_comWrappers = comWrappersToSet;
}
}
}
Expand All @@ -41,8 +53,13 @@ private static ComWrappers ComWrappers
{
lock (_comWrappersLock)
{
_comWrappers = value;
ComWrappers.RegisterForTrackerSupport(_comWrappers);
if (value == null && _comWrappers == DefaultComWrappersInstance)
{
return;
}
var comWrappersToSet = value ?? DefaultComWrappersInstance;
ComWrappers.RegisterForTrackerSupport(comWrappersToSet);
_comWrappers = comWrappersToSet;
}
}
}
Expand Down Expand Up @@ -152,7 +169,7 @@ private static T FindDelegate<T>(IntPtr thisPtr)
/// </remarks>
public static void InitializeComWrappers(ComWrappers wrappers = null)
{
ComWrappers = wrappers ?? new DefaultComWrappers();
ComWrappers = wrappers;
}

internal static Func<IInspectable, object> GetTypedRcwFactory(string runtimeClassName) => TypedObjectFactoryCache.GetOrAdd(runtimeClassName, className => CreateTypedRcwFactory(className));
Expand Down

0 comments on commit 5e14799

Please sign in to comment.