Skip to content

Commit 2119f37

Browse files
crinksdrkzu
authored andcommitted
When get proxy of classes use seperate ProxyGenerator for each namespace for performance improvement
1 parent 70619e4 commit 2119f37

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

src/Moq/Interception/CastleProxyFactory.cs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
33

44
using System;
5+
using System.Collections.Concurrent;
56
using System.Diagnostics;
67
using System.Reflection;
78

89
#if FEATURE_DEFAULT_INTERFACE_IMPLEMENTATIONS
9-
using System.Collections.Concurrent;
1010
using System.Collections.Generic;
1111
using System.Linq;
1212
using System.Reflection.Emit;
@@ -28,11 +28,19 @@ sealed class CastleProxyFactory : ProxyFactory
2828
{
2929
ProxyGenerationOptions generationOptions;
3030
ProxyGenerator generator;
31+
ConcurrentDictionary<string, ProxyGenerator> classGenerators;
3132

3233
public CastleProxyFactory()
3334
{
3435
this.generationOptions = new ProxyGenerationOptions { Hook = new IncludeObjectMethodsHook(), BaseTypeForInterfaceProxy = typeof(InterfaceProxy) };
3536
this.generator = new ProxyGenerator();
37+
this.classGenerators = new ConcurrentDictionary<string, ProxyGenerator>();
38+
}
39+
40+
ProxyGenerator GetClassGenerator(Type mockType)
41+
{
42+
var ns = mockType.Namespace ?? string.Empty;
43+
return classGenerators.GetOrAdd(ns, _ => new ProxyGenerator());
3644
}
3745

3846
/// <inheritdoc />
@@ -53,13 +61,13 @@ public override object CreateProxy(Type mockType, Moq.IInterceptor interceptor,
5361
{
5462
var options = new ProxyGenerationOptions();
5563
options.AddDelegateTypeMixin(mockType);
56-
var container = generator.CreateClassProxy(typeof(object), additionalInterfaces, options, new Interceptor(interceptor));
64+
var container = GetClassGenerator(mockType).CreateClassProxy(typeof(object), additionalInterfaces, options, new Interceptor(interceptor));
5765
return Delegate.CreateDelegate(mockType, container, container.GetType().GetMethod("Invoke"));
5866
}
5967

6068
try
6169
{
62-
return generator.CreateClassProxy(mockType, additionalInterfaces, this.generationOptions, arguments, new Interceptor(interceptor));
70+
return GetClassGenerator(mockType).CreateClassProxy(mockType, additionalInterfaces, this.generationOptions, arguments, new Interceptor(interceptor));
6371
}
6472
catch (TypeLoadException e)
6573
{

0 commit comments

Comments
 (0)