Skip to content

Commit

Permalink
Merge pull request #239 from max-ieremenko/bug-fix/design-time-depend…
Browse files Browse the repository at this point in the history
…encies

DesignTime: fix dependecies loader
  • Loading branch information
max-ieremenko authored Sep 28, 2024
2 parents b3e0b14 + e639ed0 commit 4b9cac8
Showing 1 changed file with 23 additions and 13 deletions.
36 changes: 23 additions & 13 deletions Sources/ServiceModel.Grpc.DesignTime.Generators/AssemblyResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// limitations under the License.
// </copyright>

using System.Collections.Concurrent;
using System.Reflection;
using Microsoft.CodeAnalysis.Diagnostics;

Expand All @@ -22,8 +23,10 @@ namespace ServiceModel.Grpc.DesignTime.Generators;
// workaround: custom dependencies of DesignTime.nupkg
internal sealed class AssemblyResolver : IDisposable
{
private static readonly object SyncRoot = new();
private static readonly ConcurrentDictionary<string, Assembly> LoadedByName = new(StringComparer.OrdinalIgnoreCase);

private readonly DebugLogger? _logger;
private readonly Dictionary<string, Assembly> _loadedByName;
private readonly string _dependenciesLocation;
private readonly bool _canLockFile;

Expand All @@ -33,32 +36,39 @@ public AssemblyResolver(AnalyzerConfigOptions globalOptions, DebugLogger? logger
_dependenciesLocation = GetDependenciesLocation(globalOptions);
_canLockFile = !IsLocalBuild(globalOptions);

_loadedByName = new Dictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase);

AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;
}

public void Dispose() => AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolve;

public Assembly Resolve(string assemblyName, string location)
{
if (_loadedByName.TryGetValue(assemblyName, out var result))
if (LoadedByName.TryGetValue(assemblyName, out var result))
{
return result;
}

try
{
result = Load(location);
}
catch (Exception ex)
lock (SyncRoot)
{
_logger?.Log($"AssemblyResolver: fail to load assembly {assemblyName} from {location}: {ex}");
throw;
if (LoadedByName.TryGetValue(assemblyName, out result))
{
return result;
}

try
{
result = Load(location);
}
catch (Exception ex)
{
_logger?.Log($"AssemblyResolver: fail to load assembly {assemblyName} from {location}: {ex}");
throw;
}

_logger?.Log($"AssemblyResolver: assembly {assemblyName} loaded from {location}");
LoadedByName.TryAdd(assemblyName, result);
}

_logger?.Log($"AssemblyResolver: assembly {assemblyName} loaded from {location}");
_loadedByName.Add(assemblyName, result);
return result;
}

Expand Down

0 comments on commit 4b9cac8

Please sign in to comment.