diff --git a/.gitignore b/.gitignore
index 01d2011..90fc665 100644
--- a/.gitignore
+++ b/.gitignore
@@ -22,6 +22,9 @@ x64/
# Visual Studio 2015 cache/options directory
.vs/
+# JetBrain Rider settings directory
+.idea/
+
# DNX
project.lock.json
artifacts/
diff --git a/appveyor.yml b/appveyor.yml
deleted file mode 100644
index ddf37ca..0000000
--- a/appveyor.yml
+++ /dev/null
@@ -1,32 +0,0 @@
-image: Visual Studio 2017
-configuration: Release
-platform: Any CPU
-
-install:
- - ps: $env:build_version = (Select-Xml -Path ".\package.props" -XPath "/Project/PropertyGroup/Version" | Select-Object -ExpandProperty Node).InnerText
- - ps: Update-AppveyorBuild -Version "$env:build_version.$env:APPVEYOR_BUILD_NUMBER"
-
-dotnet_csproj:
- patch: false
-
-before_build:
-- cmd: dotnet restore
-
-build:
- project: package.sln
- parallel: true
- verbosity: minimal
-
-after_build:
-- choco install opencover.portable
-- choco install codecov
-
-test_script:
-- OpenCover.Console.exe -register:user -target:"C:\Program Files\dotnet\dotnet.exe" -targetargs:"test --framework net47 --verbosity q"
-
-after_test:
-- codecov -f "results.xml"
-
-artifacts:
-- path: '**\Unity.*.nupkg'
- name: 'Unity'
diff --git a/package.props b/package.props
deleted file mode 100644
index 958f69e..0000000
--- a/package.props
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
- 5.11.1
- This package is compatible with Net Standard 2.0, Net Core 2.0, .NET 4.5, 4.6, and 4.7 frameworks.
-
-
-
- 5.11.*
- 5.11.*
-
-
-
diff --git a/src/InterceptionBehaviors/CurrentInterceptionRequest.cs b/src/Behaviors/CurrentInterceptionRequest.cs
similarity index 100%
rename from src/InterceptionBehaviors/CurrentInterceptionRequest.cs
rename to src/Behaviors/CurrentInterceptionRequest.cs
diff --git a/src/InterceptionBehaviors/IInterceptionBehavior.cs b/src/Behaviors/IInterceptionBehavior.cs
similarity index 97%
rename from src/InterceptionBehaviors/IInterceptionBehavior.cs
rename to src/Behaviors/IInterceptionBehavior.cs
index d41b9e5..621e6d9 100644
--- a/src/InterceptionBehaviors/IInterceptionBehavior.cs
+++ b/src/Behaviors/IInterceptionBehavior.cs
@@ -1,6 +1,4 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using Unity.Interception.PolicyInjection.Pipeline;
@@ -18,7 +16,7 @@ public interface IInterceptionBehavior
/// Inputs to the current call to the target.
/// Delegate to execute to get the next delegate in the behavior chain.
/// Return value from the target.
- IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext);
+ IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate? getNext);
///
/// Returns the interfaces required by the behavior for the objects it intercepts.
@@ -42,7 +40,7 @@ public interface IInterceptionBehavior
/// Inputs to the current method call.
/// Delegate to get the next interceptor in the chain.
/// Return from the next method in the chain.
- public delegate IMethodReturn InvokeInterceptionBehaviorDelegate(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext);
+ public delegate IMethodReturn InvokeInterceptionBehaviorDelegate(IMethodInvocation input, GetNextInterceptionBehaviorDelegate? getNext);
///
/// This delegate type is passed to each interceptor's Invoke method.
diff --git a/src/InterceptionBehaviors/InterceptionBehaviorPipeline.cs b/src/Behaviors/InterceptionBehaviorPipeline.cs
similarity index 84%
rename from src/InterceptionBehaviors/InterceptionBehaviorPipeline.cs
rename to src/Behaviors/InterceptionBehaviorPipeline.cs
index f4f01f4..a047dad 100644
--- a/src/InterceptionBehaviors/InterceptionBehaviorPipeline.cs
+++ b/src/Behaviors/InterceptionBehaviorPipeline.cs
@@ -1,7 +1,6 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
+using System.Reflection;
using Unity.Interception.PolicyInjection.Pipeline;
namespace Unity.Interception.InterceptionBehaviors
@@ -12,6 +11,10 @@ namespace Unity.Interception.InterceptionBehaviors
///
public class InterceptionBehaviorPipeline
{
+ internal static readonly MethodInfo AddMethodInfo = typeof(InterceptionBehaviorPipeline).GetMethod(nameof(InterceptionBehaviorPipeline.Add));
+ internal static readonly MethodInfo InvokeMethodInfo = typeof(InterceptionBehaviorPipeline).GetMethod(nameof(InterceptionBehaviorPipeline.Invoke));
+ internal static readonly ConstructorInfo DefauleConstructorInfo = typeof(InterceptionBehaviorPipeline).GetConstructor(new Type[0]);
+
private readonly List _interceptionBehaviors;
///
@@ -68,7 +71,7 @@ public IMethodReturn Invoke(IMethodInvocation input, InvokeInterceptionBehaviorD
/// Adds a to the pipeline.
///
/// The interception behavior to add.
- public void Add(IInterceptionBehavior interceptionBehavior)
+ public void Add(IInterceptionBehavior? interceptionBehavior)
{
_interceptionBehaviors.Add(interceptionBehavior ?? throw new ArgumentNullException(nameof(interceptionBehavior)));
}
diff --git a/src/ContainerIntegration/AdditionalInterface.cs b/src/ContainerIntegration/AdditionalInterface.cs
index c21cdeb..0112b67 100644
--- a/src/ContainerIntegration/AdditionalInterface.cs
+++ b/src/ContainerIntegration/AdditionalInterface.cs
@@ -45,7 +45,7 @@ public AdditionalInterface(Type additionalInterface)
/// Type to register.
/// Name used to resolve the type object.
/// Policy list to add policies to.
- public override void AddPolicies(Type registeredType, Type mappedToType, string name, ref TPolicySet policies)
+ public override void AddPolicies(Type registeredType, Type? mappedToType, string? name, ref TPolicySet policies)
{
AdditionalInterfacesPolicy policy = AdditionalInterfacesPolicy.GetOrCreate(ref policies);
policy.AddAdditionalInterface(_additionalInterface);
diff --git a/src/ContainerIntegration/InterceptionBehaviorBase.cs b/src/ContainerIntegration/InterceptionBehaviorBase.cs
index 5c9b101..a470f6c 100644
--- a/src/ContainerIntegration/InterceptionBehaviorBase.cs
+++ b/src/ContainerIntegration/InterceptionBehaviorBase.cs
@@ -13,8 +13,8 @@ namespace Unity.Interception.ContainerIntegration
///
public abstract class InterceptionBehaviorBase : InterceptionMember
{
- private readonly NamedTypeBuildKey _behaviorKey;
- private readonly IInterceptionBehavior _explicitBehavior;
+ private readonly NamedTypeBuildKey? _behaviorKey;
+ private readonly IInterceptionBehavior? _explicitBehavior;
///
/// Initializes a new instance of the with a
@@ -32,9 +32,8 @@ protected InterceptionBehaviorBase(IInterceptionBehavior interceptionBehavior)
///
/// Type of behavior to
///
- protected InterceptionBehaviorBase(Type behaviorType, string name)
+ protected InterceptionBehaviorBase(Type behaviorType, string? name)
{
- Guard.ArgumentNotNull(behaviorType, "behaviorType");
Guard.TypeIsAssignable(typeof(IInterceptionBehavior), behaviorType, "behaviorType");
_behaviorKey = new NamedTypeBuildKey(behaviorType, name);
}
@@ -57,7 +56,7 @@ protected InterceptionBehaviorBase(Type behaviorType)
/// Type to register.
/// Name used to resolve the type object.
/// Policy list to add policies to.
- public override void AddPolicies(Type registeredType, Type mappedToType, string name, ref TPolicySet policies)
+ public override void AddPolicies(Type registeredType, Type? mappedToType, string? name, ref TPolicySet policies)
{
if (_explicitBehavior != null)
{
@@ -67,7 +66,7 @@ public override void AddPolicies(Type registeredType, Type
else
{
var behaviorsPolicy = GetBehaviorsPolicy(ref policies);
- behaviorsPolicy.AddBehaviorKey(_behaviorKey);
+ behaviorsPolicy.AddBehaviorKey(_behaviorKey!);
}
}
diff --git a/src/ContainerIntegration/Interceptor.cs b/src/ContainerIntegration/Interceptor.cs
index 5b45f67..31d5817 100644
--- a/src/ContainerIntegration/Interceptor.cs
+++ b/src/ContainerIntegration/Interceptor.cs
@@ -1,11 +1,11 @@
using System;
+using System.Diagnostics;
using Unity.Interception.ContainerIntegration.ObjectBuilder;
using Unity.Interception.Interceptors;
using Unity.Interception.Interceptors.InstanceInterceptors;
using Unity.Interception.Interceptors.TypeInterceptors;
using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception;
using Unity.Interception.Utilities;
-using Unity.Storage;
namespace Unity.Interception.ContainerIntegration
{
@@ -16,9 +16,9 @@ namespace Unity.Interception.ContainerIntegration
///
public class Interceptor : InterceptionMember
{
- private readonly IInterceptor _interceptor;
- private readonly Type _type;
- private readonly string _name;
+ private readonly IInterceptor? _interceptor;
+ private readonly Type? _type;
+ private readonly string? _name;
///
/// Initializes a new instance of the class with an interceptor instance.
@@ -37,7 +37,7 @@ public Interceptor(IInterceptor interceptor)
///
/// Type of the interceptor
/// name to use to resolve.
- public Interceptor(Type interceptorType, string name)
+ public Interceptor(Type interceptorType, string? name)
{
Guard.TypeIsAssignable(typeof(IInterceptor), interceptorType ??
throw new ArgumentNullException(nameof(interceptorType)),
@@ -65,7 +65,7 @@ public Interceptor(Type interceptorType)
/// Type to register.
/// Name used to resolve the type object.
/// Policy list to add policies to.
- public override void AddPolicies(Type registeredType, Type mappedToType, string name, ref TPolicySet policies)
+ public override void AddPolicies(Type registeredType, Type? mappedToType, string? name, ref TPolicySet policies)
{
if (IsInstanceInterceptor)
{
@@ -101,7 +101,9 @@ private IInstanceInterceptionPolicy CreateInstanceInterceptionPolicy()
{
return new FixedInstanceInterceptionPolicy((IInstanceInterceptor)_interceptor);
}
- return new ResolvedInstanceInterceptionPolicy(_type, _name);
+
+ Debug.Assert(null != _type);
+ return new ResolvedInstanceInterceptionPolicy(_type!, _name);
}
private ITypeInterceptionPolicy CreateTypeInterceptionPolicy()
@@ -110,7 +112,8 @@ private ITypeInterceptionPolicy CreateTypeInterceptionPolicy()
{
return new FixedTypeInterceptionPolicy((ITypeInterceptor)_interceptor);
}
- return new ResolvedTypeInterceptionPolicy(_type, _name);
+ Debug.Assert(null != _type);
+ return new ResolvedTypeInterceptionPolicy(_type!, _name);
}
}
diff --git a/src/ContainerIntegration/ObjectBuilder/FixedTypeInterceptionPolicy.cs b/src/ContainerIntegration/ObjectBuilder/FixedTypeInterceptionPolicy.cs
index 6024e9d..4197629 100644
--- a/src/ContainerIntegration/ObjectBuilder/FixedTypeInterceptionPolicy.cs
+++ b/src/ContainerIntegration/ObjectBuilder/FixedTypeInterceptionPolicy.cs
@@ -1,7 +1,6 @@
using System;
-using Unity.Builder;
using Unity.Interception.Interceptors.TypeInterceptors;
namespace Unity.Interception.ContainerIntegration.ObjectBuilder
@@ -36,6 +35,6 @@ public ITypeInterceptor GetInterceptor(IUnityContainer container)
///
/// Cache for proxied type.
///
- public Type ProxyType { get; set; }
+ public Type? ProxyType { get; set; }
}
}
diff --git a/src/ContainerIntegration/ObjectBuilder/IInstanceInterceptionPolicy.cs b/src/ContainerIntegration/ObjectBuilder/IInstanceInterceptionPolicy.cs
index 12b89a8..3f9ed20 100644
--- a/src/ContainerIntegration/ObjectBuilder/IInstanceInterceptionPolicy.cs
+++ b/src/ContainerIntegration/ObjectBuilder/IInstanceInterceptionPolicy.cs
@@ -13,6 +13,6 @@ public interface IInstanceInterceptionPolicy
/// Interceptor to use.
///
/// Context for current build operation.
- IInstanceInterceptor GetInterceptor(ref BuilderContext context);
+ IInstanceInterceptor? GetInterceptor(ref BuilderContext context);
}
}
diff --git a/src/ContainerIntegration/ObjectBuilder/ITypeInterceptionPolicy.cs b/src/ContainerIntegration/ObjectBuilder/ITypeInterceptionPolicy.cs
index 779c631..60b3b06 100644
--- a/src/ContainerIntegration/ObjectBuilder/ITypeInterceptionPolicy.cs
+++ b/src/ContainerIntegration/ObjectBuilder/ITypeInterceptionPolicy.cs
@@ -18,7 +18,7 @@ public interface ITypeInterceptionPolicy
///
/// Cache for proxied type.
///
- Type ProxyType { get; set; }
+ Type? ProxyType { get; set; }
}
public static class TypeInterceptionPolicyExtension
diff --git a/src/ContainerIntegration/ObjectBuilder/InterceptionBehaviorsPolicy.cs b/src/ContainerIntegration/ObjectBuilder/InterceptionBehaviorsPolicy.cs
index 40180e0..28f406a 100644
--- a/src/ContainerIntegration/ObjectBuilder/InterceptionBehaviorsPolicy.cs
+++ b/src/ContainerIntegration/ObjectBuilder/InterceptionBehaviorsPolicy.cs
@@ -49,8 +49,9 @@ public IEnumerable GetEffectiveBehaviors(
foreach (var key in BehaviorKeys)
{
- var behavior = (IInterceptionBehavior)container.Resolve(key.Type, key.Name, new DependencyOverride(interceptionRequest));
- yield return behavior;
+ var behavior = (IInterceptionBehavior?)container.Resolve(key.Type, key.Name, new DependencyOverride(interceptionRequest));
+
+ if (null != behavior) yield return behavior;
}
}
@@ -67,7 +68,7 @@ public void AddBehavior(IInterceptionBehavior behavior)
internal static InterceptionBehaviorsPolicy GetOrCreate(ref TPolicySet policies)
where TPolicySet : IPolicySet
{
- IInterceptionBehaviorsPolicy policy = (IInterceptionBehaviorsPolicy)policies.Get(typeof(IInterceptionBehaviorsPolicy));
+ IInterceptionBehaviorsPolicy? policy = (IInterceptionBehaviorsPolicy?)policies.Get(typeof(IInterceptionBehaviorsPolicy));
if (!(policy is InterceptionBehaviorsPolicy))
{
diff --git a/src/ContainerIntegration/ObjectBuilder/ResolvedInstanceInterceptionPolicy.cs b/src/ContainerIntegration/ObjectBuilder/ResolvedInstanceInterceptionPolicy.cs
index 3260767..b4b225b 100644
--- a/src/ContainerIntegration/ObjectBuilder/ResolvedInstanceInterceptionPolicy.cs
+++ b/src/ContainerIntegration/ObjectBuilder/ResolvedInstanceInterceptionPolicy.cs
@@ -11,7 +11,7 @@ namespace Unity.Interception.ContainerIntegration.ObjectBuilder
public class ResolvedInstanceInterceptionPolicy : IInstanceInterceptionPolicy
{
private readonly Type _type;
- private readonly string _name;
+ private readonly string? _name;
///
/// Construct a new that
@@ -30,7 +30,7 @@ public ResolvedInstanceInterceptionPolicy(NamedTypeBuildKey buildKey)
///
/// Type of interceptor
/// Name of registration
- public ResolvedInstanceInterceptionPolicy(Type type, string name)
+ public ResolvedInstanceInterceptionPolicy(Type type, string? name)
{
_type = type;
_name = name;
@@ -42,9 +42,9 @@ public ResolvedInstanceInterceptionPolicy(Type type, string name)
/// Interceptor to use.
///
/// Context for current build operation.
- public IInstanceInterceptor GetInterceptor(ref BuilderContext context)
+ public IInstanceInterceptor? GetInterceptor(ref BuilderContext context)
{
- return (IInstanceInterceptor)context.Resolve(_type, _name);
+ return (IInstanceInterceptor?)context.Resolve(_type, _name) ;
}
#endregion
diff --git a/src/ContainerIntegration/ObjectBuilder/ResolvedTypeInterceptionPolicy.cs b/src/ContainerIntegration/ObjectBuilder/ResolvedTypeInterceptionPolicy.cs
index 090b5e4..26359f6 100644
--- a/src/ContainerIntegration/ObjectBuilder/ResolvedTypeInterceptionPolicy.cs
+++ b/src/ContainerIntegration/ObjectBuilder/ResolvedTypeInterceptionPolicy.cs
@@ -13,8 +13,8 @@ namespace Unity.Interception.ContainerIntegration.ObjectBuilder
public class ResolvedTypeInterceptionPolicy : ITypeInterceptionPolicy
{
private readonly Type _type;
- private readonly string _name;
- private ITypeInterceptor _policy;
+ private readonly string? _name;
+ private ITypeInterceptor? _policy;
///
/// construct a new that
@@ -33,7 +33,7 @@ public ResolvedTypeInterceptionPolicy(NamedTypeBuildKey buildKey)
///
/// Type of the policy
/// Name of the registration
- public ResolvedTypeInterceptionPolicy(Type type, string name)
+ public ResolvedTypeInterceptionPolicy(Type type, string? name)
{
_type = type;
_name = name;
@@ -48,7 +48,7 @@ public ResolvedTypeInterceptionPolicy(Type type, string name)
public ITypeInterceptor GetInterceptor(IUnityContainer container)
{
if (null == _policy)
- _policy = (ITypeInterceptor)container.Resolve(_type, _name, null);
+ _policy = (ITypeInterceptor?)container.Resolve(_type, _name)!;
return _policy;
}
@@ -56,7 +56,7 @@ public ITypeInterceptor GetInterceptor(IUnityContainer container)
///
/// Cache for proxied type.
///
- public Type ProxyType { get; set; }
+ public Type? ProxyType { get; set; }
#endregion
}
diff --git a/src/ContainerIntegration/PolicyDefinition.cs b/src/ContainerIntegration/PolicyDefinition.cs
index 75a69a2..8b8a59f 100644
--- a/src/ContainerIntegration/PolicyDefinition.cs
+++ b/src/ContainerIntegration/PolicyDefinition.cs
@@ -4,7 +4,6 @@
using Unity.Interception.PolicyInjection.MatchingRules;
using Unity.Interception.PolicyInjection.Pipeline;
using Unity.Interception.PolicyInjection.Policies;
-using Unity.Interception.Utilities;
using Unity.Lifetime;
namespace Unity.Interception.ContainerIntegration
@@ -504,41 +503,27 @@ public PolicyDefinition AddCallHandler(
private PolicyDefinition AddElement(string name, UpdateElements update)
{
- Guard.ArgumentNotNull(name, "name");
-
- return update(name);
+ return update(name ?? throw new ArgumentNullException(nameof(name)));
}
private PolicyDefinition AddElement(T instance, UpdateElements update)
{
- Guard.ArgumentNotNull(instance, "instance");
-
string newName = NewName();
- Container.RegisterInstance(newName, instance);
+ Container.RegisterInstance(newName, instance ?? throw new ArgumentNullException(nameof(instance)));
return update(newName);
}
- private PolicyDefinition AddElement(
- Type type,
- string name,
- LifetimeManager lifetimeManager,
- InjectionMember[] injectionMembers,
- UpdateElements update)
+ private PolicyDefinition AddElement( Type type, string name, LifetimeManager? lifetimeManager, InjectionMember[] injectionMembers, UpdateElements update)
{
- Guard.ArgumentNotNullOrEmpty(name, "name");
- Guard.ArgumentNotNull(type, "type");
- Guard.TypeIsAssignable(typeof(T), type, "type");
- Guard.ArgumentNotNull(injectionMembers, "injectionMembers");
-
- Container.RegisterType(typeof(T), type, name, (ITypeLifetimeManager)lifetimeManager, injectionMembers);
+ Container.RegisterType(typeof(T), type, name, (ITypeLifetimeManager?)lifetimeManager, injectionMembers);
return update(name);
}
private PolicyDefinition AddElement(
string name,
- LifetimeManager lifetimeManager,
+ LifetimeManager? lifetimeManager,
InjectionMember[] injectionMembers,
UpdateElements update)
where TElement : T
diff --git a/src/ContainerIntegration/Selection/SelectedConstructor.cs b/src/ContainerIntegration/Selection/SelectedConstructor.cs
deleted file mode 100644
index 811d557..0000000
--- a/src/ContainerIntegration/Selection/SelectedConstructor.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using Unity.Injection;
-
-namespace Unity.Interception.ContainerIntegration.Selection
-{
- ///
- /// Objects of this type encapsulate and resolve
- /// parameters.
- ///
- public class SelectedConstructor : MethodBase
- {
- ///
- /// Create a new instance which
- /// contains the given constructor.
- ///
- /// The constructor to wrap.
- public SelectedConstructor(ConstructorInfo constructor)
- : base(constructor)
- {
- }
-
- public SelectedConstructor(ConstructorInfo info, object[] parameters)
- : base(info, parameters)
- {
- }
-
- ///
- /// The constructor this object wraps.
- ///
- public ConstructorInfo Constructor => Selection;
-
-
- #region Overrides
-
- public override IEnumerable DeclaredMembers(Type type)
- {
-#if NETCOREAPP1_0 || NETSTANDARD1_0
- return type.GetTypeInfo().DeclaredConstructors
- .Where(c => c.IsStatic == false && c.IsPublic);
-#else
- return type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
-#endif
- }
-
- #endregion
- }
-}
diff --git a/src/Intercept.cs b/src/Intercept.cs
index ed3ec9d..23572dd 100644
--- a/src/Intercept.cs
+++ b/src/Intercept.cs
@@ -7,7 +7,6 @@
using Unity.Interception.Interceptors.InstanceInterceptors;
using Unity.Interception.Interceptors.TypeInterceptors;
using Unity.Interception.Properties;
-using Unity.Interception.Utilities;
namespace Unity.Interception
{
@@ -89,11 +88,11 @@ public static object ThroughProxyWithAdditionalInterfaces(
IEnumerable interceptionBehaviors,
IEnumerable additionalInterfaces)
{
- Guard.ArgumentNotNull(interceptedType, "interceptedType");
- Guard.ArgumentNotNull(target, "target");
- Guard.ArgumentNotNull(interceptor, "interceptor");
- Guard.ArgumentNotNull(interceptionBehaviors, "interceptionBehaviors");
- Guard.ArgumentNotNull(additionalInterfaces, "additionalInterfaces");
+ if (null == interceptedType) throw new ArgumentNullException(nameof(interceptedType));
+ if (null == target) throw new ArgumentNullException(nameof(target));
+ if (null == interceptor) throw new ArgumentNullException(nameof(interceptor));
+ if (null == interceptionBehaviors) throw new ArgumentNullException(nameof(interceptionBehaviors));
+ if (null == additionalInterfaces) throw new ArgumentNullException(nameof(additionalInterfaces));
if (!interceptor.CanIntercept(interceptedType))
{
@@ -233,10 +232,10 @@ public static object NewInstanceWithAdditionalInterfaces(
IEnumerable additionalInterfaces,
params object[] constructorParameters)
{
- Guard.ArgumentNotNull(type, "type");
- Guard.ArgumentNotNull(interceptor, "interceptor");
- Guard.ArgumentNotNull(interceptionBehaviors, "interceptionBehaviors");
- Guard.ArgumentNotNull(additionalInterfaces, "additionalInterfaces");
+ if (null == type) throw new ArgumentNullException(nameof(type));
+ if (null == interceptor) throw new ArgumentNullException(nameof(interceptor));
+ if (null == interceptionBehaviors) throw new ArgumentNullException(nameof(interceptionBehaviors));
+ if (null == additionalInterfaces) throw new ArgumentNullException(nameof(additionalInterfaces));
if (!interceptor.CanIntercept(type))
{
diff --git a/src/Interception.cs b/src/Interception.cs
index 7f6e1e1..c3098af 100644
--- a/src/Interception.cs
+++ b/src/Interception.cs
@@ -10,7 +10,6 @@
using Unity.Interception.PolicyInjection;
using Unity.Interception.PolicyInjection.Policies;
using Unity.Interception.Properties;
-using Unity.Interception.Utilities;
namespace Unity.Interception
{
@@ -46,10 +45,11 @@ protected override void Initialize()
/// Name type is registered under.
/// Interceptor to use.
/// This extension object.
- public Interception SetInterceptorFor(Type typeToIntercept, string name, ITypeInterceptor interceptor)
+ public Interception SetInterceptorFor(Type typeToIntercept, string? name, ITypeInterceptor interceptor)
{
- Guard.ArgumentNotNull(typeToIntercept, "typeToIntercept");
- Guard.ArgumentNotNull(interceptor, "interceptor");
+ if (null == typeToIntercept) throw new ArgumentNullException(nameof(typeToIntercept));
+ if (null == interceptor) throw new ArgumentNullException(nameof(interceptor));
+
GuardTypeInterceptable(typeToIntercept, interceptor);
var key = new NamedTypeBuildKey(typeToIntercept, name);
@@ -83,7 +83,7 @@ public Interception SetInterceptorFor(Type typeToIntercept, ITypeInterceptor int
/// Name type is registered under.
/// Interceptor object to use.
/// This extension object.
- public Interception SetInterceptorFor(string name, ITypeInterceptor interceptor)
+ public Interception SetInterceptorFor(string? name, ITypeInterceptor interceptor)
{
return SetInterceptorFor(typeof(T), name, interceptor);
}
@@ -106,10 +106,11 @@ public Interception SetInterceptorFor(ITypeInterceptor interceptor)
/// Name type is registered under.
/// Instance interceptor to use.
/// This extension object.
- public Interception SetInterceptorFor(Type typeToIntercept, string name, IInstanceInterceptor interceptor)
+ public Interception SetInterceptorFor(Type typeToIntercept, string? name, IInstanceInterceptor interceptor)
{
- Guard.ArgumentNotNull(typeToIntercept, "typeToIntercept");
- Guard.ArgumentNotNull(interceptor, "interceptor");
+ if (null == typeToIntercept) throw new ArgumentNullException(nameof(typeToIntercept));
+ if (null == interceptor) throw new ArgumentNullException(nameof(interceptor));
+
GuardTypeInterceptable(typeToIntercept, interceptor);
var key = new NamedTypeBuildKey(typeToIntercept, name);
@@ -133,8 +134,9 @@ public Interception SetInterceptorFor(Type typeToIntercept, string name, IInstan
/// This extension object.
public Interception SetDefaultInterceptorFor(Type typeToIntercept, ITypeInterceptor interceptor)
{
- Guard.ArgumentNotNull(typeToIntercept, "typeToIntercept");
- Guard.ArgumentNotNull(interceptor, "interceptor");
+ if (null == typeToIntercept) throw new ArgumentNullException(nameof(typeToIntercept));
+ if (null == interceptor) throw new ArgumentNullException(nameof(interceptor));
+
GuardTypeInterceptable(typeToIntercept, interceptor);
Context.Policies.Set(typeToIntercept, UnityContainer.All, typeof(ITypeInterceptionPolicy),
@@ -177,7 +179,7 @@ public Interception SetInterceptorFor(Type typeToIntercept, IInstanceInterceptor
/// Name type is registered under.
/// Instance interceptor to use.
/// This extension object.
- public Interception SetInterceptorFor(string name, IInstanceInterceptor interceptor)
+ public Interception SetInterceptorFor(string? name, IInstanceInterceptor interceptor)
{
return SetInterceptorFor(typeof(T), name, interceptor);
}
@@ -201,8 +203,9 @@ public Interception SetInterceptorFor(IInstanceInterceptor interceptor)
/// This extension object.
public Interception SetDefaultInterceptorFor(Type typeToIntercept, IInstanceInterceptor interceptor)
{
- Guard.ArgumentNotNull(typeToIntercept, "typeToIntercept");
- Guard.ArgumentNotNull(interceptor, "interceptor");
+ if (null == typeToIntercept) throw new ArgumentNullException(nameof(typeToIntercept));
+ if (null == interceptor) throw new ArgumentNullException(nameof(interceptor));
+
GuardTypeInterceptable(typeToIntercept, interceptor);
Context.Policies.Set(typeToIntercept, UnityContainer.All, typeof(IInstanceInterceptionPolicy), new FixedInstanceInterceptionPolicy(interceptor));
@@ -252,7 +255,9 @@ private static void GuardTypeInterceptable(Type typeToIntercept, IInterceptor in
///
public PolicyDefinition AddPolicy(string policyName)
{
- Guard.ArgumentNotNullOrEmpty(policyName, "policyName");
+ if (null == policyName) throw new ArgumentNullException(nameof(policyName));
+ if (0 == policyName.Length) throw new ArgumentException(@"The provided string argument must not be empty.", policyName);
+
return new PolicyDefinition(policyName, this);
}
}
diff --git a/src/Interceptors/GenericParameterMapper.cs b/src/Interceptors/GenericParameterMapper.cs
index 70bbfdd..2c3e3ec 100644
--- a/src/Interceptors/GenericParameterMapper.cs
+++ b/src/Interceptors/GenericParameterMapper.cs
@@ -1,10 +1,7 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Interception.Properties;
-using Unity.Interception.Utilities;
namespace Unity.Interception.Interceptors
{
@@ -17,7 +14,7 @@ public class GenericParameterMapper
private readonly IDictionary _mappedTypesCache = new Dictionary();
private readonly ICollection> _localMappings;
- private readonly GenericParameterMapper _parent;
+ private readonly GenericParameterMapper? _parent;
///
/// Initializes a new instance of the class.
@@ -26,7 +23,7 @@ public class GenericParameterMapper
/// The parent mapper, or .
public GenericParameterMapper(Type type, GenericParameterMapper parent)
{
- Guard.ArgumentNotNull(type, "type");
+ if (null == type) throw new ArgumentNullException(nameof(type));
if (type.IsGenericType)
{
@@ -63,7 +60,7 @@ public GenericParameterMapper(Type[] reflectedParameters, Type[] generatedParame
/// The reflected generic parameters.
/// The generated generic parameters.
/// The parent mapper, or .
- public GenericParameterMapper(Type[] reflectedParameters, Type[] generatedParameters, GenericParameterMapper parent)
+ public GenericParameterMapper(Type[] reflectedParameters, Type[] generatedParameters, GenericParameterMapper? parent)
{
_parent = parent;
_localMappings = CreateMappings(reflectedParameters, generatedParameters);
@@ -71,8 +68,8 @@ public GenericParameterMapper(Type[] reflectedParameters, Type[] generatedParame
private static ICollection> CreateMappings(Type[] reflectedParameters, Type[] generatedParameters)
{
- Guard.ArgumentNotNull(reflectedParameters, "reflectedParameters");
- Guard.ArgumentNotNull(generatedParameters, "generatedParameters");
+ if (null == reflectedParameters) throw new ArgumentNullException(nameof(reflectedParameters));
+ if (null == generatedParameters) throw new ArgumentNullException(nameof(generatedParameters));
if (reflectedParameters.Length != generatedParameters.Length)
{
diff --git a/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceImplementation.cs b/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceImplementation.cs
index c2ace43..a365aec 100644
--- a/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceImplementation.cs
+++ b/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceImplementation.cs
@@ -17,7 +17,7 @@ internal class InterfaceImplementation
private readonly GenericParameterMapper _genericParameterMapper;
private readonly FieldBuilder _proxyInterceptionPipelineField;
private readonly bool _explicitImplementation;
- private readonly FieldBuilder _targetField;
+ private readonly FieldBuilder? _targetField;
public InterfaceImplementation(
TypeBuilder typeBuilder,
@@ -32,7 +32,7 @@ public InterfaceImplementation(
Type @interface,
FieldBuilder proxyInterceptionPipelineField,
bool explicitImplementation,
- FieldBuilder targetField)
+ FieldBuilder? targetField)
: this(typeBuilder, @interface, GenericParameterMapper.DefaultMapper, proxyInterceptionPipelineField, explicitImplementation, targetField)
{ }
@@ -42,7 +42,7 @@ public InterfaceImplementation(
GenericParameterMapper genericParameterMapper,
FieldBuilder proxyInterceptionPipelineField,
bool explicitImplementation,
- FieldBuilder targetField)
+ FieldBuilder? targetField)
{
_typeBuilder = typeBuilder;
_interface = @interface;
@@ -57,8 +57,10 @@ public InterfaceImplementation(
// in this case, the targetInterface is a constructed version using the generic type parameters
// from the generated type generate type
var definition = @interface.GetGenericTypeDefinition();
+
Debug.Assert(definition != null, nameof(definition) + " != null");
- var mappedParameters = definition.GetGenericArguments().Select(t => genericParameterMapper.Map(t)).ToArray();
+
+ var mappedParameters = definition!.GetGenericArguments().Select(t => genericParameterMapper.Map(t)).ToArray();
_targetInterface = definition.MakeGenericType(mappedParameters);
}
else
@@ -144,12 +146,12 @@ private IEnumerable PropertiesToIntercept()
private void OverrideProperty(PropertyInfo property, int count)
{
- MethodBuilder getMethod = OverridePropertyMethod(property.GetGetMethod(), count);
- MethodBuilder setMethod = OverridePropertyMethod(property.GetSetMethod(), count);
+ MethodBuilder? getMethod = OverridePropertyMethod(property.GetGetMethod(), count);
+ MethodBuilder? setMethod = OverridePropertyMethod(property.GetSetMethod(), count);
AddPropertyDefinition(property, getMethod, setMethod);
}
- private void AddPropertyDefinition(PropertyInfo property, MethodBuilder getMethod, MethodBuilder setMethod)
+ private void AddPropertyDefinition(PropertyInfo property, MethodBuilder? getMethod, MethodBuilder? setMethod)
{
PropertyBuilder newProperty =
_typeBuilder.DefineProperty(
@@ -169,7 +171,7 @@ private void AddPropertyDefinition(PropertyInfo property, MethodBuilder getMetho
}
}
- private MethodBuilder OverridePropertyMethod(MethodInfo method, int count)
+ private MethodBuilder? OverridePropertyMethod(MethodInfo method, int count)
{
return method == null
? null
@@ -193,12 +195,12 @@ private IEnumerable EventsToIntercept()
private void OverrideEvent(EventInfo @event, int count)
{
- MethodBuilder addMethod = OverrideEventMethod(@event.GetAddMethod(), count);
- MethodBuilder removeMethod = OverrideEventMethod(@event.GetRemoveMethod(), count);
+ MethodBuilder? addMethod = OverrideEventMethod(@event.GetAddMethod(), count);
+ MethodBuilder? removeMethod = OverrideEventMethod(@event.GetRemoveMethod(), count);
AddEventDefinition(@event, addMethod, removeMethod);
}
- private void AddEventDefinition(EventInfo @event, MethodBuilder addMethod, MethodBuilder removeMethod)
+ private void AddEventDefinition(EventInfo @event, MethodBuilder? addMethod, MethodBuilder? removeMethod)
{
EventBuilder newEvent = _typeBuilder.DefineEvent(@event.Name, @event.Attributes, @event.EventHandlerType);
@@ -213,7 +215,7 @@ private void AddEventDefinition(EventInfo @event, MethodBuilder addMethod, Metho
}
}
- private MethodBuilder OverrideEventMethod(MethodInfo method, int count)
+ private MethodBuilder? OverrideEventMethod(MethodInfo method, int count)
{
return method == null
? null
diff --git a/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceInterceptor.cs b/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceInterceptor.cs
index 42259ef..403a3f6 100644
--- a/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceInterceptor.cs
+++ b/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceInterceptor.cs
@@ -1,10 +1,7 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using System.Reflection;
using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration;
-using Unity.Interception.Utilities;
namespace Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception
{
@@ -26,7 +23,8 @@ public class InterfaceInterceptor : IInstanceInterceptor
/// True if interception is possible, false if not.
public bool CanIntercept(Type t)
{
- Guard.ArgumentNotNull(t, "t");
+ if (null == t) throw new ArgumentNullException(nameof(t));
+
return t.IsInterface;
}
@@ -42,8 +40,8 @@ public IEnumerable GetInterceptableMethods(
Type interceptedType,
Type implementationType)
{
- Guard.ArgumentNotNull(interceptedType, "interceptedType");
- Guard.ArgumentNotNull(implementationType, "implementationType");
+ if (null == interceptedType) throw new ArgumentNullException(nameof(interceptedType));
+ if (null == implementationType) throw new ArgumentNullException(nameof(implementationType));
return DoGetInterceptableMethods(interceptedType, implementationType);
}
@@ -88,8 +86,8 @@ private IEnumerable DoGetInterceptableMethods(
/// The proxy object.
public IInterceptingProxy CreateProxy(Type t, object target, params Type[] additionalInterfaces)
{
- Guard.ArgumentNotNull(t, "t");
- Guard.ArgumentNotNull(additionalInterfaces, "additionalInterfaces");
+ if (null == t) throw new ArgumentNullException(nameof(t));
+ if (null == additionalInterfaces) throw new ArgumentNullException(nameof(additionalInterfaces));
Type interceptorType;
Type typeToProxy = t;
diff --git a/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceInterceptorClassGenerator.cs b/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceInterceptorClassGenerator.cs
index 1f2ba20..03e29a2 100644
--- a/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceInterceptorClassGenerator.cs
+++ b/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceInterceptorClassGenerator.cs
@@ -1,6 +1,4 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
@@ -10,6 +8,8 @@
using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration;
using Unity.Interception.Properties;
using Unity.Interception.Utilities;
+using Unity.Interception.InterceptionBehaviors;
+using System.Diagnostics;
namespace Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception
{
@@ -19,15 +19,18 @@ namespace Unity.Interception.Interceptors.InstanceInterceptors.InterfaceIntercep
///
public partial class InterfaceInterceptorClassGenerator
{
+ private static readonly ConstructorInfo ObjectConstructorInfo =
+ typeof(object).GetConstructor(new Type[0]);
+
private static readonly AssemblyBuilder AssemblyBuilder;
private readonly Type _typeToIntercept;
private readonly IEnumerable _additionalInterfaces;
- private GenericParameterMapper _mainInterfaceMapper;
+ private readonly GenericParameterMapper _mainInterfaceMapper;
- private FieldBuilder _proxyInterceptionPipelineField;
- private FieldBuilder _targetField;
- private FieldBuilder _typeToProxyField;
- private TypeBuilder _typeBuilder;
+ private readonly FieldBuilder _proxyInterceptionPipelineField;
+ private readonly FieldBuilder _targetField;
+ private readonly FieldBuilder _typeToProxyField;
+ private readonly TypeBuilder _typeBuilder;
static InterfaceInterceptorClassGenerator()
{
@@ -35,6 +38,7 @@ static InterfaceInterceptorClassGenerator()
using (MemoryStream ms = new MemoryStream())
{
+ // TODO: "Unity.Interception.package.snk"
typeof(InterfaceInterceptorClassGenerator)
.Assembly
.GetManifestResourceStream("Unity.Interception.package.snk")
@@ -65,7 +69,17 @@ public InterfaceInterceptorClassGenerator(Type typeToIntercept, IEnumerable additionalInterfaces)
@@ -129,7 +143,9 @@ public Type CreateProxyType()
AddConstructor();
- Type result = _typeBuilder.CreateTypeInfo().AsType();
+ var info = _typeBuilder.CreateTypeInfo(); Debug.Assert(null != info);
+ Type result = info!.AsType();
+
#if DEBUG_SAVE_GENERATED_ASSEMBLY
assemblyBuilder.Save("Unity_ILEmit_InterfaceProxies.dll");
#endif
@@ -138,7 +154,7 @@ public Type CreateProxyType()
private void AddConstructor()
{
- Type[] paramTypes = Sequence.Collect(_typeToIntercept, typeof(Type)).ToArray();
+ var paramTypes = new Type[] { _typeToIntercept, typeof(Type) };
ConstructorBuilder ctorBuilder = _typeBuilder.DefineConstructor(
MethodAttributes.Public,
@@ -152,11 +168,11 @@ private void AddConstructor()
// Call base class constructor
il.Emit(OpCodes.Ldarg_0);
- il.Emit(OpCodes.Call, ObjectMethods.Constructor);
+ il.Emit(OpCodes.Call, ObjectConstructorInfo);
// Initialize pipeline field
il.Emit(OpCodes.Ldarg_0);
- il.Emit(OpCodes.Newobj, InterceptionBehaviorPipelineMethods.Constructor);
+ il.Emit(OpCodes.Newobj, InterceptionBehaviorPipeline.DefauleConstructorInfo);
il.Emit(OpCodes.Stfld, _proxyInterceptionPipelineField);
// Initialize the target field
@@ -172,20 +188,6 @@ private void AddConstructor()
il.Emit(OpCodes.Ret);
}
- private void CreateTypeBuilder()
- {
- TypeAttributes newAttributes = TypeAttributes.Public | TypeAttributes.Class;
-
- ModuleBuilder moduleBuilder = InterceptorClassGenerator.CreateModuleBuilder(AssemblyBuilder);
- _typeBuilder = moduleBuilder.DefineType(CreateTypeName(), newAttributes);
-
- _mainInterfaceMapper = DefineGenericArguments();
-
- _proxyInterceptionPipelineField = InterceptingProxyImplementor.ImplementIInterceptingProxy(_typeBuilder);
- _targetField = _typeBuilder.DefineField("target", _typeToIntercept, FieldAttributes.Private);
- _typeToProxyField = _typeBuilder.DefineField("typeToProxy", typeof(Type), FieldAttributes.Private);
- }
-
private string CreateTypeName()
{
return "DynamicModule.ns.Wrapped_" + _typeToIntercept.Name + "_" + Guid.NewGuid().ToString("N");
diff --git a/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceMethodOverride.cs b/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceMethodOverride.cs
index 8ce6504..e05b316 100644
--- a/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceMethodOverride.cs
+++ b/src/Interceptors/InstanceInterceptors/InterfaceInterception/InterfaceMethodOverride.cs
@@ -1,17 +1,15 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
+using System.Runtime.CompilerServices;
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception;
using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration;
using Unity.Interception.PolicyInjection.Pipeline;
using Unity.Interception.Properties;
-using Unity.Interception.Utilities;
namespace Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception
{
@@ -21,7 +19,36 @@ namespace Unity.Interception.Interceptors.InstanceInterceptors.InterfaceIntercep
public class InterfaceMethodOverride
{
private static readonly MethodInfo BuildAdditionalInterfaceNonImplementedExceptionMethod =
- StaticReflection.GetMethodInfo(() => BuildAdditionalInterfaceNonImplementedException());
+ typeof(InterfaceMethodOverride).GetMethod(nameof(InterfaceMethodOverride.BuildAdditionalInterfaceNonImplementedException));
+ private static readonly MethodInfo CreateExceptionMethodReturnMethod =
+ typeof(IMethodInvocation).GetMethod(nameof(IMethodInvocation.CreateExceptionMethodReturn));
+ private static readonly MethodInfo CreateReturnMethod =
+ typeof(IMethodInvocation).GetMethod(nameof(IMethodInvocation.CreateMethodReturn));
+ private static readonly MethodInfo GetArgumentsMethod =
+ typeof(IMethodInvocation).GetProperty(nameof(IMethodInvocation.Arguments)).GetGetMethod();
+ private static readonly ConstructorInfo CompilerGeneratedAttributeCtor =
+ typeof(CompilerGeneratedAttribute).GetConstructor(new Type[0]);
+ private static readonly MethodInfo GetExceptionMethod =
+ typeof(IMethodReturn).GetProperty(nameof(IMethodReturn.Exception)).GetGetMethod();
+ private static readonly MethodInfo GetReturnValueMethod =
+ typeof(IMethodReturn).GetProperty(nameof(IMethodReturn.ReturnValue)).GetGetMethod();
+ private static readonly MethodInfo GetOutputsMethod =
+ typeof(IMethodReturn).GetProperty(nameof(IMethodReturn.Outputs)).GetGetMethod();
+ private static readonly MethodInfo GetMethodFromHandleMethod =
+ typeof(MethodBase).GetMethod(nameof(MethodBase.GetMethodFromHandle), new Type []{ typeof(RuntimeMethodHandle) });
+ private static readonly MethodInfo GetMethodForGenericFromHandleMethod =
+ typeof(MethodBase).GetMethod(nameof(MethodBase.GetMethodFromHandle), new Type[] { typeof(RuntimeMethodHandle), typeof(RuntimeTypeHandle) });
+ private static readonly MethodInfo GetItemMethod =
+ typeof(System.Collections.IList).GetProperty("Item").GetGetMethod();
+ private static readonly MethodInfo ExceptionDispatchInfoCaptureMethod =
+ typeof(System.Runtime.ExceptionServices.ExceptionDispatchInfo)
+ .GetMethod(nameof(System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture), new Type[] { typeof(Exception) });
+ private static readonly MethodInfo ExceptionDispatchInfoThrowMethod =
+ typeof(System.Runtime.ExceptionServices.ExceptionDispatchInfo)
+ .GetMethod(nameof(System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw), new Type[0]);
+ private static readonly ConstructorInfo InvokeInterceptionBehaviorDelegateCtor = typeof(InvokeInterceptionBehaviorDelegate)
+ .GetConstructor(new Type[] { typeof(object), typeof(IntPtr) });
+
private const MethodAttributes ImplicitImplementationAttributes =
MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final
@@ -35,7 +62,7 @@ public class InterfaceMethodOverride
private readonly ParameterInfo[] _methodParameters;
private readonly FieldBuilder _proxyInterceptionPipelineField;
private readonly bool _explicitImplementation;
- private readonly FieldBuilder _targetField;
+ private readonly FieldBuilder? _targetField;
private readonly Type _targetInterface;
private readonly GenericParameterMapper _targetInterfaceParameterMapper;
private readonly int _overrideCount;
@@ -43,7 +70,7 @@ public class InterfaceMethodOverride
internal InterfaceMethodOverride(
TypeBuilder typeBuilder,
FieldBuilder proxyInterceptionPipelineField,
- FieldBuilder targetField,
+ FieldBuilder? targetField,
MethodInfo methodToOverride,
Type targetInterface,
GenericParameterMapper targetInterfaceParameterMapper,
@@ -137,6 +164,8 @@ private static void EmitUnboxOrCast(ILGenerator il, Type targetType)
}
}
+// TODO: Enable warning
+#pragma warning disable CS8604 // Possible null reference argument.
private MethodBuilder CreateDelegateImplementation()
{
string methodName = CreateMethodName("DelegateImplementation");
@@ -156,7 +185,7 @@ private MethodBuilder CreateDelegateImplementation()
// Parameter
methodBuilder.DefineParameter(2, ParameterAttributes.None, "getNext");
- methodBuilder.SetCustomAttribute(new CustomAttributeBuilder(CompilerGeneratedAttributeMethods.CompilerGeneratedAttribute, new object[0]));
+ methodBuilder.SetCustomAttribute(new CustomAttributeBuilder(CompilerGeneratedAttributeCtor, new object[0]));
ILGenerator il = methodBuilder.GetILGenerator();
@@ -166,8 +195,8 @@ private MethodBuilder CreateDelegateImplementation()
Label done = il.DefineLabel();
LocalBuilder ex = il.DeclareLocal(typeof(Exception));
- LocalBuilder baseReturn = null;
- LocalBuilder parameters = null;
+ LocalBuilder? baseReturn = null;
+ LocalBuilder? parameters = null;
if (MethodHasReturnValue)
{
@@ -184,14 +213,14 @@ private MethodBuilder CreateDelegateImplementation()
{
parameters = il.DeclareLocal(typeof(IParameterCollection));
il.Emit(OpCodes.Ldarg_1);
- il.EmitCall(OpCodes.Callvirt, IMethodInvocationMethods.GetArguments, null);
+ il.EmitCall(OpCodes.Callvirt, GetArgumentsMethod, null);
il.Emit(OpCodes.Stloc, parameters);
for (int i = 0; i < _methodParameters.Length; ++i)
{
il.Emit(OpCodes.Ldloc, parameters);
EmitLoadConstant(il, i);
- il.EmitCall(OpCodes.Callvirt, IListMethods.GetItem, null);
+ il.EmitCall(OpCodes.Callvirt, GetItemMethod, null);
Type parameterType = paramMapper.GetParameterType(_methodParameters[i].ParameterType);
if (parameterType.IsByRef)
@@ -259,21 +288,21 @@ private MethodBuilder CreateDelegateImplementation()
{
il.Emit(OpCodes.Ldloc, parameters);
EmitLoadConstant(il, i);
- il.Emit(OpCodes.Callvirt, IListMethods.GetItem);
+ il.Emit(OpCodes.Callvirt, GetItemMethod);
}
il.Emit(OpCodes.Stelem_Ref);
}
il.Emit(OpCodes.Ldloc, outputArguments);
}
- il.Emit(OpCodes.Callvirt, IMethodInvocationMethods.CreateReturn);
+ il.Emit(OpCodes.Callvirt, CreateReturnMethod);
il.Emit(OpCodes.Stloc, retval);
il.BeginCatchBlock(typeof(Exception));
il.Emit(OpCodes.Stloc, ex);
// Create an exception return
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldloc, ex);
- il.EmitCall(OpCodes.Callvirt, IMethodInvocationMethods.CreateExceptionMethodReturn, null);
+ il.EmitCall(OpCodes.Callvirt, CreateExceptionMethodReturnMethod, null);
il.Emit(OpCodes.Stloc, retval);
il.EndExceptionBlock();
il.MarkLabel(done);
@@ -285,11 +314,12 @@ private MethodBuilder CreateDelegateImplementation()
// exception-throwing implementation
il.Emit(OpCodes.Ldarg_1);
il.EmitCall(OpCodes.Call, BuildAdditionalInterfaceNonImplementedExceptionMethod, null);
- il.EmitCall(OpCodes.Callvirt, IMethodInvocationMethods.CreateExceptionMethodReturn, null);
+ il.EmitCall(OpCodes.Callvirt, CreateExceptionMethodReturnMethod, null);
il.Emit(OpCodes.Ret);
}
return methodBuilder;
}
+#pragma warning restore CS8604 // Possible null reference argument.
private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
{
@@ -349,11 +379,11 @@ private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
{
// if the declaring type is generic, we need to get the method from the target type
il.Emit(OpCodes.Ldtoken, _targetInterface);
- il.Emit(OpCodes.Call, MethodBaseMethods.GetMethodForGenericFromHandle);
+ il.Emit(OpCodes.Call, GetMethodForGenericFromHandleMethod);
}
else
{
- il.Emit(OpCodes.Call, MethodBaseMethods.GetMethodFromHandle); // target method
+ il.Emit(OpCodes.Call, GetMethodFromHandleMethod); // target method
}
EmitLoadConstant(il, _methodParameters.Length);
@@ -379,7 +409,7 @@ private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
il.Emit(OpCodes.Ldloc, parameterArray);
}
- il.Emit(OpCodes.Newobj, VirtualMethodInvocationMethods.VirtualMethodInvocation);
+ il.Emit(OpCodes.Newobj, VirtualMethodInvocation.ConstructorInfo);
il.Emit(OpCodes.Stloc, inputs);
il.Emit(OpCodes.Ldarg_0);
@@ -397,17 +427,17 @@ private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
il.Emit(OpCodes.Ldftn, callTarget);
- il.Emit(OpCodes.Newobj, InvokeInterceptionBehaviorDelegateMethods.InvokeInterceptionBehaviorDelegate);
+ il.Emit(OpCodes.Newobj, InvokeInterceptionBehaviorDelegateCtor);
// And call the pipeline
- il.Emit(OpCodes.Call, InterceptionBehaviorPipelineMethods.Invoke);
+ il.Emit(OpCodes.Call, InterceptionBehaviorPipeline.InvokeMethodInfo);
il.Emit(OpCodes.Stloc, methodReturn);
// Was there an exception?
Label noException = il.DefineLabel();
il.Emit(OpCodes.Ldloc, methodReturn);
- il.EmitCall(OpCodes.Callvirt, IMethodReturnMethods.GetException, null);
+ il.EmitCall(OpCodes.Callvirt, GetExceptionMethod, null);
il.Emit(OpCodes.Stloc, ex);
il.Emit(OpCodes.Ldloc, ex);
il.Emit(OpCodes.Ldnull);
@@ -415,11 +445,11 @@ private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
il.Emit(OpCodes.Brtrue_S, noException);
il.Emit(OpCodes.Ldloc, ex);
- if (ReflectionHelper.ExceptionDispatchInfoCaptureMethod != null
- && ReflectionHelper.ExceptionDispatchInfoThrowMethod != null)
+ if (ExceptionDispatchInfoCaptureMethod != null
+ && ExceptionDispatchInfoThrowMethod != null)
{
- il.EmitCall(OpCodes.Call, ReflectionHelper.ExceptionDispatchInfoCaptureMethod, null);
- il.EmitCall(OpCodes.Callvirt, ReflectionHelper.ExceptionDispatchInfoThrowMethod, null);
+ il.EmitCall(OpCodes.Call, ExceptionDispatchInfoCaptureMethod, null);
+ il.EmitCall(OpCodes.Callvirt, ExceptionDispatchInfoThrowMethod, null);
}
else
{
@@ -442,9 +472,9 @@ private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
// GetOrDefault the value of this output parameter out of the Outputs collection
il.Emit(OpCodes.Ldloc, methodReturn);
- il.Emit(OpCodes.Callvirt, IMethodReturnMethods.GetOutputs);
+ il.Emit(OpCodes.Callvirt, GetOutputsMethod);
EmitLoadConstant(il, outputArgNum++);
- il.Emit(OpCodes.Callvirt, IListMethods.GetItem);
+ il.Emit(OpCodes.Callvirt, GetItemMethod);
EmitUnboxOrCast(il, paramMapper.GetElementType(pi.ParameterType));
// And store in the caller
@@ -456,7 +486,7 @@ private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
if (MethodHasReturnValue)
{
il.Emit(OpCodes.Ldloc, methodReturn);
- il.EmitCall(OpCodes.Callvirt, IMethodReturnMethods.GetReturnValue, null);
+ il.EmitCall(OpCodes.Callvirt, GetReturnValueMethod, null);
EmitUnboxOrCast(il, paramMapper.GetReturnType());
}
il.Emit(OpCodes.Ret);
diff --git a/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/InterceptingRealProxy.cs b/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/InterceptingRealProxy.cs
index 80bf316..ed3680a 100644
--- a/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/InterceptingRealProxy.cs
+++ b/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/InterceptingRealProxy.cs
@@ -1,6 +1,4 @@
-// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
-
-using System;
+using System;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Runtime.Remoting;
@@ -11,7 +9,6 @@
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.PolicyInjection.Pipeline;
using Unity.Interception.Properties;
-using Unity.Interception.Utilities;
namespace Unity.Interception.Interceptors.InstanceInterceptors.TransparentProxyInterception
{
@@ -40,8 +37,7 @@ public InterceptingRealProxy(
params Type[] additionalInterfaces)
: base(classToProxy)
{
- Guard.ArgumentNotNull(target, "target");
- Target = target;
+ Target = target ?? throw new ArgumentNullException(nameof(target));
_additionalInterfaces = CheckAdditionalInterfaces(additionalInterfaces);
TypeName = target.GetType().FullName;
}
@@ -66,7 +62,7 @@ private static ReadOnlyCollection CheckAdditionalInterfaces(Type[] interfa
[SecuritySafeCritical]
public void AddInterceptionBehavior(IInterceptionBehavior interceptor)
{
- Guard.ArgumentNotNull(interceptor, "interceptor");
+ if (null == interceptor) throw new ArgumentNullException(nameof(interceptor));
_interceptorsPipeline.Add(interceptor);
}
@@ -87,8 +83,8 @@ public void AddInterceptionBehavior(IInterceptionBehavior interceptor)
[SecurityCritical]
public bool CanCastTo(Type fromType, object o)
{
- Guard.ArgumentNotNull(fromType, "fromType");
- Guard.ArgumentNotNull(o, "o");
+ if (null == fromType) throw new ArgumentNullException(nameof(fromType));
+ if (null == o) throw new ArgumentNullException(nameof(o));
if (fromType == typeof(IInterceptingProxy))
{
@@ -142,7 +138,7 @@ public string TypeName
[SecurityCritical]
public override IMessage Invoke(IMessage msg)
{
- Guard.ArgumentNotNull(msg, "msg");
+ if (null == msg) throw new ArgumentNullException(nameof(msg));
IMethodCallMessage callMessage = (IMethodCallMessage)msg;
@@ -155,7 +151,7 @@ public override IMessage Invoke(IMessage msg)
IMethodReturn result =
_interceptorsPipeline.Invoke(
invocation,
- delegate(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
+ delegate(IMethodInvocation input, GetNextInterceptionBehaviorDelegate? getNext)
{
if (callMessage.MethodBase.DeclaringType.IsAssignableFrom(Target.GetType()))
{
@@ -180,12 +176,11 @@ public override IMessage Invoke(IMessage msg)
private IMessage HandleInterceptingProxyMethod(IMethodCallMessage callMessage)
{
- switch (callMessage.MethodName)
+ return callMessage.MethodName switch
{
- case "AddInterceptionBehavior":
- return ExecuteAddInterceptionBehavior(callMessage);
- }
- throw new InvalidOperationException();
+ "AddInterceptionBehavior" => ExecuteAddInterceptionBehavior(callMessage),
+ _ => throw new InvalidOperationException(),
+ };
}
private IMessage ExecuteAddInterceptionBehavior(IMethodCallMessage callMessage)
diff --git a/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/TransparentProxyInterceptor.cs b/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/TransparentProxyInterceptor.cs
index 5c65b15..4f06a3b 100644
--- a/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/TransparentProxyInterceptor.cs
+++ b/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/TransparentProxyInterceptor.cs
@@ -1,11 +1,8 @@
-// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
-
-using System;
+using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting.Proxies;
using System.Security;
-using Unity.Interception.Utilities;
namespace Unity.Interception.Interceptors.InstanceInterceptors.TransparentProxyInterception
{
@@ -22,7 +19,7 @@ public class TransparentProxyInterceptor : IInstanceInterceptor
/// True if interception is possible, false if not.
public bool CanIntercept(Type t)
{
- Guard.ArgumentNotNull(t, "t");
+ if (null == t) throw new ArgumentNullException(nameof(t));
return (typeof(MarshalByRefObject).IsAssignableFrom(t) || t.IsInterface);
}
@@ -91,8 +88,8 @@ private static bool IsNotSystemMethod(MethodInfo method)
[SecuritySafeCritical]
public IInterceptingProxy CreateProxy(Type t, object target, params Type[] additionalInterfaces)
{
- Guard.ArgumentNotNull(t, "t");
- Guard.ArgumentNotNull(target, "target");
+ if (null == t) throw new ArgumentNullException(nameof(t));
+ if (null == target) throw new ArgumentNullException(nameof(target));
RealProxy realProxy = new InterceptingRealProxy(target, t, additionalInterfaces);
return (IInterceptingProxy)realProxy.GetTransparentProxy();
diff --git a/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/TransparentProxyMethodInvocation.cs b/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/TransparentProxyMethodInvocation.cs
index 1d283cc..3ad7825 100644
--- a/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/TransparentProxyMethodInvocation.cs
+++ b/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/TransparentProxyMethodInvocation.cs
@@ -1,13 +1,10 @@
-// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
-
-using System;
+using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Security;
using System.Security.Permissions;
using Unity.Interception.PolicyInjection.Pipeline;
-using Unity.Interception.Utilities;
namespace Unity.Interception.Interceptors.InstanceInterceptors.TransparentProxyInterception
{
@@ -36,9 +33,7 @@ public sealed class TransparentProxyMethodInvocation : IMethodInvocation
/// Ultimate target of the method call.
public TransparentProxyMethodInvocation(IMethodCallMessage callMessage, object target)
{
- Guard.ArgumentNotNull(callMessage, "callMessage");
-
- _callMessage = callMessage;
+ _callMessage = callMessage ?? throw new ArgumentNullException(nameof(callMessage));
_invocationContext = new Dictionary();
_target = target;
_arguments = callMessage.Args;
diff --git a/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/TransparentProxyMethodReturn.cs b/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/TransparentProxyMethodReturn.cs
index 087fd4b..eb2f4bd 100644
--- a/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/TransparentProxyMethodReturn.cs
+++ b/src/Interceptors/InstanceInterceptors/TransparentProxyInterception/TransparentProxyMethodReturn.cs
@@ -1,6 +1,4 @@
-// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
-
-using System;
+using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
@@ -22,8 +20,8 @@ internal class TransparentProxyMethodReturn : IMethodReturn
private readonly ParameterCollection _outputs;
private readonly IDictionary _invocationContext;
private readonly object[] _arguments;
- private object _returnValue;
- private Exception _exception;
+ private object? _returnValue;
+ private Exception? _exception;
///
/// Creates a new object that contains a
@@ -75,7 +73,7 @@ public IParameterCollection Outputs
///
/// This value is null if the method has no return value.
/// The return value.
- public object ReturnValue
+ public object? ReturnValue
{
[SecuritySafeCritical]
get { return _returnValue; }
@@ -91,7 +89,7 @@ public object ReturnValue
/// If the method threw an exception, the exception object is here.
///
/// The exception, or null if no exception was thrown.
- public Exception Exception
+ public Exception? Exception
{
[SecuritySafeCritical]
get { return _exception; }
diff --git a/src/Interceptors/MethodImplementationInfo.cs b/src/Interceptors/MethodImplementationInfo.cs
index f18bd7a..ab7a511 100644
--- a/src/Interceptors/MethodImplementationInfo.cs
+++ b/src/Interceptors/MethodImplementationInfo.cs
@@ -18,7 +18,7 @@ public class MethodImplementationInfo
///
/// MethodInfo for the interface method (may be null if no interface).
/// MethodInfo for implementing method.
- public MethodImplementationInfo(MethodInfo interfaceMethodInfo, MethodInfo implementationMethodInfo)
+ public MethodImplementationInfo(MethodInfo? interfaceMethodInfo, MethodInfo implementationMethodInfo)
{
InterfaceMethodInfo = interfaceMethodInfo;
ImplementationMethodInfo = implementationMethodInfo;
@@ -27,7 +27,7 @@ public MethodImplementationInfo(MethodInfo interfaceMethodInfo, MethodInfo imple
///
/// The interface method MethodInfo.
///
- public MethodInfo InterfaceMethodInfo { get; }
+ public MethodInfo? InterfaceMethodInfo { get; }
///
/// The implementing method MethodInfo.
@@ -43,15 +43,12 @@ public MethodImplementationInfo(MethodInfo interfaceMethodInfo, MethodInfo imple
/// The to compare with the current .
/// The parameter is null.
/// 2
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
- MethodImplementationInfo other = obj as MethodImplementationInfo;
- if (obj == null || other == null)
- {
- return false;
- }
+ if (obj is MethodImplementationInfo other)
+ return this == other;
- return this == other;
+ return false;
}
///
@@ -73,18 +70,18 @@ public override int GetHashCode()
///
public static bool operator ==(MethodImplementationInfo left, MethodImplementationInfo right)
{
- if (ReferenceEquals(left, null) && ReferenceEquals(right, null))
+ if (left is null && right is null)
{
return true;
}
- if (ReferenceEquals(left, null) || ReferenceEquals(right, null))
+ if (left is null || right is null)
{
return false;
}
return left.InterfaceMethodInfo == right.InterfaceMethodInfo &&
- left.ImplementationMethodInfo == right.ImplementationMethodInfo;
+ left.ImplementationMethodInfo == right.ImplementationMethodInfo;
}
///
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/CompilerGeneratedAttributeMethods.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/CompilerGeneratedAttributeMethods.cs
deleted file mode 100644
index a7e5d0c..0000000
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/CompilerGeneratedAttributeMethods.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Unity.Interception.Utilities;
-
-namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration
-{
- internal static class CompilerGeneratedAttributeMethods
- {
- public static ConstructorInfo CompilerGeneratedAttribute
- {
- get { return StaticReflection.GetConstructorInfo(() => new CompilerGeneratedAttribute()); }
- }
- }
-}
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/IInterceptingProxyMethods.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/IInterceptingProxyMethods.cs
deleted file mode 100644
index d265bd5..0000000
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/IInterceptingProxyMethods.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
-using System.Reflection;
-using Unity.Interception.Utilities;
-
-namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration
-{
- internal static class IInterceptingProxyMethods
- {
- internal static MethodInfo AddInterceptionBehavior
- {
- get { return StaticReflection.GetMethodInfo(ip => ip.AddInterceptionBehavior(null)); }
- }
- }
-}
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/IListMethods.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/IListMethods.cs
deleted file mode 100644
index 21fcd85..0000000
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/IListMethods.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-using System.Collections;
-using System.Reflection;
-
-namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration
-{
- internal static class IListMethods
- {
- internal static MethodInfo GetItem => typeof(IList).GetProperty("Item")?.GetGetMethod();
- }
-}
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/IMethodInvocationMethods.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/IMethodInvocationMethods.cs
deleted file mode 100644
index f427314..0000000
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/IMethodInvocationMethods.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-
-
-using System;
-using System.Reflection;
-using Unity.Interception.PolicyInjection.Pipeline;
-using Unity.Interception.Utilities;
-
-namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration
-{
- ///
- /// MethodInfo objects for the methods we need to generate
- /// calls to on IMethodInvocation.
- ///
- internal static class IMethodInvocationMethods
- {
- internal static MethodInfo CreateExceptionMethodReturn
- {
- get { return StaticReflection.GetMethodInfo((IMethodInvocation mi) => mi.CreateExceptionMethodReturn(default(Exception))); }
- }
-
- internal static MethodInfo CreateReturn => typeof(IMethodInvocation).GetMethod("CreateMethodReturn");
-
- internal static MethodInfo GetArguments
- {
- get { return StaticReflection.GetPropertyGetMethodInfo((IMethodInvocation mi) => mi.Arguments); }
- }
- }
-}
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/IMethodReturnMethods.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/IMethodReturnMethods.cs
deleted file mode 100644
index 37b3ab8..0000000
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/IMethodReturnMethods.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-using System.Reflection;
-using Unity.Interception.PolicyInjection.Pipeline;
-using Unity.Interception.Utilities;
-
-namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration
-{
- internal static class IMethodReturnMethods
- {
- internal static MethodInfo GetException
- {
- get { return StaticReflection.GetPropertyGetMethodInfo((IMethodReturn imr) => imr.Exception); }
- }
-
- internal static MethodInfo GetReturnValue
- {
- get { return StaticReflection.GetPropertyGetMethodInfo((IMethodReturn imr) => imr.ReturnValue); }
- }
-
- internal static MethodInfo GetOutputs
- {
- get { return StaticReflection.GetPropertyGetMethodInfo((IMethodReturn imr) => imr.Outputs); }
- }
- }
-}
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InterceptingClassGenerator.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InterceptingClassGenerator.cs
index b7b53e4..46abf13 100644
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InterceptingClassGenerator.cs
+++ b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InterceptingClassGenerator.cs
@@ -4,9 +4,11 @@
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
+using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception;
namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration
@@ -20,11 +22,11 @@ public partial class InterceptingClassGenerator
private readonly Type _typeToIntercept;
private readonly IEnumerable _additionalInterfaces;
- private Type _targetType;
- private GenericParameterMapper _mainTypeMapper;
+ private readonly Type _targetType;
+ private readonly GenericParameterMapper _mainTypeMapper;
- private FieldBuilder _proxyInterceptionPipelineField;
- private TypeBuilder _typeBuilder;
+ private readonly FieldBuilder _proxyInterceptionPipelineField;
+ private readonly TypeBuilder _typeBuilder;
static InterceptingClassGenerator()
{
@@ -47,7 +49,32 @@ public InterceptingClassGenerator(Type typeToIntercept, params Type[] additional
{
_typeToIntercept = typeToIntercept;
_additionalInterfaces = additionalInterfaces;
- CreateTypeBuilder();
+
+ TypeAttributes newAttributes = _typeToIntercept.Attributes;
+ newAttributes = FilterTypeAttributes(newAttributes);
+
+ Type baseClass = GetGenericType(_typeToIntercept);
+
+ ModuleBuilder moduleBuilder = InterceptorClassGenerator.CreateModuleBuilder(AssemblyBuilder);
+ _typeBuilder = moduleBuilder.DefineType(
+ "DynamicModule.ns.Wrapped_" + _typeToIntercept.Name + "_" + Guid.NewGuid().ToString("N"),
+ newAttributes,
+ baseClass);
+
+ _mainTypeMapper = DefineGenericArguments(_typeBuilder, baseClass);
+
+ if (_typeToIntercept.IsGenericType)
+ {
+ var definition = _typeToIntercept.GetGenericTypeDefinition();
+ var mappedParameters = definition.GetGenericArguments().Select(t => _mainTypeMapper.Map(t)).ToArray();
+ _targetType = definition.MakeGenericType(mappedParameters);
+ }
+ else
+ {
+ _targetType = _typeToIntercept;
+ }
+
+ _proxyInterceptionPipelineField = InterceptingProxyImplementor.ImplementIInterceptingProxy(_typeBuilder);
}
///
@@ -66,11 +93,11 @@ public Type GenerateType()
foreach (var @interface in _additionalInterfaces)
{
memberCount =
- new InterfaceImplementation(_typeBuilder, @interface, _proxyInterceptionPipelineField, true)
+ new InterfaceImplementation(_typeBuilder!, @interface, _proxyInterceptionPipelineField, true)
.Implement(implementedInterfaces, memberCount);
}
- Type result = _typeBuilder.CreateTypeInfo().AsType();
+ Type result = _typeBuilder!.CreateTypeInfo()!.AsType() ;
#if DEBUG_SAVE_GENERATED_ASSEMBLY
assemblyBuilder.Save("Unity_ILEmit_DynamicClasses.dll");
#endif
@@ -192,7 +219,7 @@ private void AddConstructor(ConstructorInfo ctor)
// Initialize pipeline field
il.Emit(OpCodes.Ldarg_0);
- il.Emit(OpCodes.Newobj, InterceptionBehaviorPipelineMethods.Constructor);
+ il.Emit(OpCodes.Newobj, InterceptionBehaviorPipeline.DefauleConstructorInfo);
il.Emit(OpCodes.Stfld, _proxyInterceptionPipelineField);
// call base class constructor
@@ -207,35 +234,6 @@ private void AddConstructor(ConstructorInfo ctor)
il.Emit(OpCodes.Ret);
}
- private void CreateTypeBuilder()
- {
- TypeAttributes newAttributes = _typeToIntercept.Attributes;
- newAttributes = FilterTypeAttributes(newAttributes);
-
- Type baseClass = GetGenericType(_typeToIntercept);
-
- ModuleBuilder moduleBuilder = InterceptorClassGenerator.CreateModuleBuilder(AssemblyBuilder);
- _typeBuilder = moduleBuilder.DefineType(
- "DynamicModule.ns.Wrapped_" + _typeToIntercept.Name + "_" + Guid.NewGuid().ToString("N"),
- newAttributes,
- baseClass);
-
- _mainTypeMapper = DefineGenericArguments(_typeBuilder, baseClass);
-
- if (_typeToIntercept.IsGenericType)
- {
- var definition = _typeToIntercept.GetGenericTypeDefinition();
- var mappedParameters = definition.GetGenericArguments().Select(t => _mainTypeMapper.Map(t)).ToArray();
- _targetType = definition.MakeGenericType(mappedParameters);
- }
- else
- {
- _targetType = _typeToIntercept;
- }
-
- _proxyInterceptionPipelineField = InterceptingProxyImplementor.ImplementIInterceptingProxy(_typeBuilder);
- }
-
private static Type GetGenericType(Type typeToIntercept)
{
if (typeToIntercept.IsGenericType)
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InterceptingProxyImplementor.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InterceptingProxyImplementor.cs
index 55744fe..4a6cbc5 100644
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InterceptingProxyImplementor.cs
+++ b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InterceptingProxyImplementor.cs
@@ -12,6 +12,8 @@ namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodIntercep
///
internal static class InterceptingProxyImplementor
{
+ private static readonly MethodInfo AddInterceptionBehaviorMethod = typeof(IInterceptingProxy).GetMethod(nameof(IInterceptingProxy.AddInterceptionBehavior));
+
internal static FieldBuilder ImplementIInterceptingProxy(TypeBuilder typeBuilder)
{
typeBuilder.AddInterfaceImplementation(typeof(IInterceptingProxy));
@@ -50,9 +52,9 @@ private static void ImplementAddInterceptionBehavior(TypeBuilder typeBuilder, Fi
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, proxyInterceptorPipelineField);
il.Emit(OpCodes.Ldarg_1);
- il.EmitCall(OpCodes.Callvirt, InterceptionBehaviorPipelineMethods.Add, null);
+ il.EmitCall(OpCodes.Callvirt, InterceptionBehaviorPipeline.AddMethodInfo, null);
il.Emit(OpCodes.Ret);
- typeBuilder.DefineMethodOverride(methodBuilder, IInterceptingProxyMethods.AddInterceptionBehavior);
+ typeBuilder.DefineMethodOverride(methodBuilder, AddInterceptionBehaviorMethod);
}
}
}
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InterceptionBehaviorPipelineMethods.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InterceptionBehaviorPipelineMethods.cs
deleted file mode 100644
index 5cba785..0000000
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InterceptionBehaviorPipelineMethods.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-using System.Reflection;
-using Unity.Interception.InterceptionBehaviors;
-using Unity.Interception.Utilities;
-
-namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration
-{
- internal static class InterceptionBehaviorPipelineMethods
- {
- internal static ConstructorInfo Constructor
- {
- get { return StaticReflection.GetConstructorInfo(() => new InterceptionBehaviorPipeline()); }
- }
-
- internal static MethodInfo Add
- {
- get { return StaticReflection.GetMethodInfo((InterceptionBehaviorPipeline pip) => pip.Add(null)); }
- }
-
- internal static MethodInfo Invoke
- {
- get { return StaticReflection.GetMethodInfo((InterceptionBehaviorPipeline pip) => pip.Invoke(null, null)); }
- }
- }
-}
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InvokeInterceptionBehaviorDelegateMethods.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InvokeInterceptionBehaviorDelegateMethods.cs
deleted file mode 100644
index 6f957df..0000000
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/InvokeInterceptionBehaviorDelegateMethods.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
-using System;
-using System.Reflection;
-using Unity.Interception.InterceptionBehaviors;
-using Unity.Interception.Utilities;
-
-namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration
-{
- internal static class InvokeInterceptionBehaviorDelegateMethods
- {
- internal static ConstructorInfo InvokeInterceptionBehaviorDelegate => typeof(InvokeInterceptionBehaviorDelegate)
- .GetConstructor(Sequence.Collect(typeof(object), typeof(IntPtr)));
- }
-}
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodBaseMethods.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodBaseMethods.cs
deleted file mode 100644
index 2056f7a..0000000
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodBaseMethods.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-using System;
-using System.Reflection;
-using Unity.Interception.Utilities;
-
-namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration
-{
- internal static class MethodBaseMethods
- {
- internal static MethodInfo GetMethodFromHandle
- {
- get
- {
- return StaticReflection.GetMethodInfo(
- () => MethodBase.GetMethodFromHandle(default(RuntimeMethodHandle)));
- }
- }
-
- internal static MethodInfo GetMethodForGenericFromHandle
- {
- get
- {
- return StaticReflection.GetMethodInfo(
- () => MethodBase.GetMethodFromHandle(default(RuntimeMethodHandle), default(RuntimeTypeHandle)));
- }
- }
- }
-}
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodOverride.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodOverride.cs
index fdc33de..b71207b 100644
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodOverride.cs
+++ b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodOverride.cs
@@ -1,16 +1,13 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
+using System.Runtime.CompilerServices;
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.PolicyInjection.Pipeline;
using Unity.Interception.Properties;
-using Unity.Interception.Utilities;
namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration
{
@@ -19,8 +16,37 @@ namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodIntercep
///
public class MethodOverride
{
- private static readonly MethodInfo BuildAbstractMethodInvokedExceptionMethod =
- StaticReflection.GetMethodInfo(() => BuildAbstractMethodInvokedException());
+ private static readonly MethodInfo BuildAbstractMethodInvokedExceptionMethod =
+ typeof(MethodOverride).GetMethod(nameof(MethodOverride.BuildAbstractMethodInvokedException));
+ private static readonly MethodInfo CreateExceptionMethodReturnMethod =
+ typeof(IMethodInvocation).GetMethod(nameof(IMethodInvocation.CreateExceptionMethodReturn));
+ private static readonly MethodInfo CreateReturnMethod =
+ typeof(IMethodInvocation).GetMethod(nameof(IMethodInvocation.CreateMethodReturn));
+ private static readonly MethodInfo GetArgumentsMethod =
+ typeof(IMethodInvocation).GetProperty(nameof(IMethodInvocation.Arguments)).GetGetMethod();
+ private static readonly ConstructorInfo CompilerGeneratedAttributeCtor =
+ typeof(CompilerGeneratedAttribute).GetConstructor(new Type[0]);
+ private static readonly MethodInfo GetExceptionMethod =
+ typeof(IMethodReturn).GetProperty(nameof(IMethodReturn.Exception)).GetGetMethod();
+ private static readonly MethodInfo GetReturnValueMethod =
+ typeof(IMethodReturn).GetProperty(nameof(IMethodReturn.ReturnValue)).GetGetMethod();
+ private static readonly MethodInfo GetOutputsMethod =
+ typeof(IMethodReturn).GetProperty(nameof(IMethodReturn.Outputs)).GetGetMethod();
+ private static readonly MethodInfo GetMethodFromHandleMethod =
+ typeof(MethodBase).GetMethod(nameof(MethodBase.GetMethodFromHandle), new Type[] { typeof(RuntimeMethodHandle) });
+ private static readonly MethodInfo GetMethodForGenericFromHandleMethod =
+ typeof(MethodBase).GetMethod(nameof(MethodBase.GetMethodFromHandle), new Type[] { typeof(RuntimeMethodHandle), typeof(RuntimeTypeHandle) });
+ private static readonly MethodInfo GetItemMethod =
+ typeof(System.Collections.IList).GetProperty("Item").GetGetMethod();
+ private static readonly MethodInfo ExceptionDispatchInfoCaptureMethod =
+ typeof(System.Runtime.ExceptionServices.ExceptionDispatchInfo)
+ .GetMethod(nameof(System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture), new Type[] { typeof(Exception) });
+ private static readonly MethodInfo ExceptionDispatchInfoThrowMethod =
+ typeof(System.Runtime.ExceptionServices.ExceptionDispatchInfo)
+ .GetMethod(nameof(System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw), new Type[0]);
+ private static readonly ConstructorInfo InvokeInterceptionBehaviorDelegateCtor = typeof(InvokeInterceptionBehaviorDelegate)
+ .GetConstructor(new Type[] { typeof(object), typeof(IntPtr) });
+
private readonly TypeBuilder _typeBuilder;
private readonly MethodInfo _methodToOverride;
@@ -144,6 +170,8 @@ private static void EmitUnboxOrCast(ILGenerator il, Type typeOnStack)
}
}
+// TODO: enable warning
+#pragma warning disable CS8604 // Possible null reference argument.
private MethodBuilder CreateDelegateImplementation(MethodInfo callBaseMethod)
{
string methodName = CreateMethodName("DelegateImplementation");
@@ -163,7 +191,7 @@ private MethodBuilder CreateDelegateImplementation(MethodInfo callBaseMethod)
// Parameter
methodBuilder.DefineParameter(2, ParameterAttributes.None, "getNext");
- methodBuilder.SetCustomAttribute(new CustomAttributeBuilder(CompilerGeneratedAttributeMethods.CompilerGeneratedAttribute, new object[0]));
+ methodBuilder.SetCustomAttribute(new CustomAttributeBuilder(CompilerGeneratedAttributeCtor, new object[0]));
ILGenerator il = methodBuilder.GetILGenerator();
@@ -172,8 +200,8 @@ private MethodBuilder CreateDelegateImplementation(MethodInfo callBaseMethod)
Label done = il.DefineLabel();
LocalBuilder ex = il.DeclareLocal(typeof(Exception));
- LocalBuilder baseReturn = null;
- LocalBuilder parameters = null;
+ LocalBuilder? baseReturn = null;
+ LocalBuilder? parameters = null;
if (MethodHasReturnValue)
{
baseReturn = il.DeclareLocal(paramMapper.GetParameterType(_methodToOverride.ReturnType));
@@ -188,14 +216,14 @@ private MethodBuilder CreateDelegateImplementation(MethodInfo callBaseMethod)
{
parameters = il.DeclareLocal(typeof(IParameterCollection));
il.Emit(OpCodes.Ldarg_1);
- il.EmitCall(OpCodes.Callvirt, IMethodInvocationMethods.GetArguments, null);
+ il.EmitCall(OpCodes.Callvirt, GetArgumentsMethod, null);
il.Emit(OpCodes.Stloc, parameters);
for (int i = 0; i < _methodParameters.Length; ++i)
{
il.Emit(OpCodes.Ldloc, parameters);
EmitLoadConstant(il, i);
- il.EmitCall(OpCodes.Callvirt, IListMethods.GetItem, null);
+ il.EmitCall(OpCodes.Callvirt, GetItemMethod, null);
if (_methodParameters[i].ParameterType.IsByRef)
{
@@ -270,21 +298,21 @@ private MethodBuilder CreateDelegateImplementation(MethodInfo callBaseMethod)
{
il.Emit(OpCodes.Ldloc, parameters);
EmitLoadConstant(il, paramNum);
- il.Emit(OpCodes.Callvirt, IListMethods.GetItem);
+ il.Emit(OpCodes.Callvirt, GetItemMethod);
}
il.Emit(OpCodes.Stelem_Ref);
}
il.Emit(OpCodes.Ldloc, outputParamArray);
}
- il.Emit(OpCodes.Callvirt, IMethodInvocationMethods.CreateReturn);
+ il.Emit(OpCodes.Callvirt, CreateReturnMethod);
il.Emit(OpCodes.Stloc, retval);
il.BeginCatchBlock(typeof(Exception));
il.Emit(OpCodes.Stloc, ex);
// Create an exception return
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldloc, ex);
- il.EmitCall(OpCodes.Callvirt, IMethodInvocationMethods.CreateExceptionMethodReturn, null);
+ il.EmitCall(OpCodes.Callvirt, CreateExceptionMethodReturnMethod, null);
il.Emit(OpCodes.Stloc, retval);
il.EndExceptionBlock();
il.MarkLabel(done);
@@ -296,15 +324,14 @@ private MethodBuilder CreateDelegateImplementation(MethodInfo callBaseMethod)
// exception-throwing implementation
il.Emit(OpCodes.Ldarg_1);
il.EmitCall(OpCodes.Call, BuildAbstractMethodInvokedExceptionMethod, null);
- il.EmitCall(OpCodes.Callvirt, IMethodInvocationMethods.CreateExceptionMethodReturn, null);
+ il.EmitCall(OpCodes.Callvirt, CreateExceptionMethodReturnMethod, null);
il.Emit(OpCodes.Ret);
}
return methodBuilder;
}
+#pragma warning restore CS8604 // Possible null reference argument.
- [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling",
- Justification = "Possibly agree with this, but requires more deliberate refactoring")]
private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
{
MethodAttributes attrs =
@@ -345,11 +372,11 @@ private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
{
// if the declaring type is generic, we need to get the method from the target type
il.Emit(OpCodes.Ldtoken, _targetType);
- il.Emit(OpCodes.Call, MethodBaseMethods.GetMethodForGenericFromHandle);
+ il.Emit(OpCodes.Call, GetMethodForGenericFromHandleMethod);
}
else
{
- il.Emit(OpCodes.Call, MethodBaseMethods.GetMethodFromHandle); // target method
+ il.Emit(OpCodes.Call, GetMethodFromHandleMethod); // target method
}
EmitLoadConstant(il, _methodParameters.Length);
@@ -382,7 +409,7 @@ private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
il.Emit(OpCodes.Ldloc, parameterArray);
}
- il.Emit(OpCodes.Newobj, VirtualMethodInvocationMethods.VirtualMethodInvocation);
+ il.Emit(OpCodes.Newobj, VirtualMethodInvocation.ConstructorInfo);
il.Emit(OpCodes.Stloc, inputs);
il.Emit(OpCodes.Ldarg_0);
@@ -399,17 +426,17 @@ private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
}
il.Emit(OpCodes.Ldftn, invokeTarget);
- il.Emit(OpCodes.Newobj, InvokeInterceptionBehaviorDelegateMethods.InvokeInterceptionBehaviorDelegate);
+ il.Emit(OpCodes.Newobj, InvokeInterceptionBehaviorDelegateCtor);
// And call the pipeline
- il.Emit(OpCodes.Call, InterceptionBehaviorPipelineMethods.Invoke);
+ il.Emit(OpCodes.Call, InterceptionBehaviorPipeline.InvokeMethodInfo);
il.Emit(OpCodes.Stloc, methodReturn);
// Was there an exception?
Label noException = il.DefineLabel();
il.Emit(OpCodes.Ldloc, methodReturn);
- il.EmitCall(OpCodes.Callvirt, IMethodReturnMethods.GetException, null);
+ il.EmitCall(OpCodes.Callvirt, GetExceptionMethod, null);
il.Emit(OpCodes.Stloc, ex);
il.Emit(OpCodes.Ldloc, ex);
il.Emit(OpCodes.Ldnull);
@@ -417,11 +444,11 @@ private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
il.Emit(OpCodes.Brtrue_S, noException);
il.Emit(OpCodes.Ldloc, ex);
- if (ReflectionHelper.ExceptionDispatchInfoCaptureMethod != null
- && ReflectionHelper.ExceptionDispatchInfoThrowMethod != null)
+ if (ExceptionDispatchInfoCaptureMethod != null
+ && ExceptionDispatchInfoThrowMethod != null)
{
- il.EmitCall(OpCodes.Call, ReflectionHelper.ExceptionDispatchInfoCaptureMethod, null);
- il.EmitCall(OpCodes.Callvirt, ReflectionHelper.ExceptionDispatchInfoThrowMethod, null);
+ il.EmitCall(OpCodes.Call, ExceptionDispatchInfoCaptureMethod, null);
+ il.EmitCall(OpCodes.Callvirt, ExceptionDispatchInfoThrowMethod, null);
}
else
{
@@ -434,7 +461,7 @@ private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
if (MethodHasReturnValue)
{
il.Emit(OpCodes.Ldloc, methodReturn);
- il.EmitCall(OpCodes.Callvirt, IMethodReturnMethods.GetReturnValue, null);
+ il.EmitCall(OpCodes.Callvirt, GetReturnValueMethod, null);
if (ReturnType.IsValueType || ReturnType.IsGenericParameter)
{
il.Emit(OpCodes.Unbox_Any, paramMapper.GetReturnType());
@@ -457,9 +484,9 @@ private MethodBuilder CreateMethodOverride(MethodBuilder delegateMethod)
// GetOrDefault result of output parameter out of the results array
il.Emit(OpCodes.Ldloc, methodReturn);
- il.Emit(OpCodes.Callvirt, IMethodReturnMethods.GetOutputs);
+ il.Emit(OpCodes.Callvirt, GetOutputsMethod);
EmitLoadConstant(il, outArgIndex);
- il.Emit(OpCodes.Callvirt, IListMethods.GetItem);
+ il.Emit(OpCodes.Callvirt, GetItemMethod);
EmitUnboxOrCast(il, elementType);
// And store the results
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodOverrideParameterMapper.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodOverrideParameterMapper.cs
index cde4206..ba71b8a 100644
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodOverrideParameterMapper.cs
+++ b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodOverrideParameterMapper.cs
@@ -1,6 +1,7 @@
using System;
+using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
@@ -16,7 +17,7 @@ namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodIntercep
internal class MethodOverrideParameterMapper
{
private readonly MethodInfo _methodToOverride;
- private GenericParameterMapper _genericParameterMapper;
+ private GenericParameterMapper? _genericParameterMapper;
public MethodOverrideParameterMapper(MethodInfo methodToOverride)
{
@@ -63,7 +64,8 @@ public void SetupParameters(MethodBuilder methodBuilder, GenericParameterMapper
public Type GetParameterType(Type originalParameterType)
{
- return _genericParameterMapper.Map(originalParameterType);
+ Debug.Assert(null != _genericParameterMapper);
+ return _genericParameterMapper!.Map(originalParameterType);
}
public Type GetElementType(Type originalParameterType)
@@ -76,6 +78,13 @@ public Type GetReturnType()
return GetParameterType(_methodToOverride.ReturnType);
}
- public Type[] GenericMethodParameters => _genericParameterMapper.GetGeneratedParameters();
+ public Type[] GenericMethodParameters
+ {
+ get
+ {
+ Debug.Assert(null != _genericParameterMapper);
+ return _genericParameterMapper!.GetGeneratedParameters();
+ }
+ }
}
}
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodSorter.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodSorter.cs
index 3aaa0c1..774bad7 100644
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodSorter.cs
+++ b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/MethodSorter.cs
@@ -95,8 +95,11 @@ private static IEnumerable> GroupOverloadedMethods(IList overloads = new List();
- overloads.Add(sortedMethods[overloadStart]);
+ List overloads = new List
+ {
+ sortedMethods[overloadStart]
+ };
+
++index;
while (index < sortedMethods.Count &&
CompareMethodInfosByParameterLists(sortedMethods[overloadStart], sortedMethods[index]) == 0)
@@ -121,18 +124,20 @@ private MethodInfo SelectMostDerivedOverload(IList overloads)
}
int minDepth = int.MaxValue;
- MethodInfo selectedMethod = null;
+ MethodInfo? selectedMethod = null;
+
foreach (MethodInfo method in overloads)
{
int thisDepth = DeclarationDepth(method);
if (thisDepth < minDepth)
- {
+ {
minDepth = thisDepth;
selectedMethod = method;
}
}
- return selectedMethod;
+ System.Diagnostics.Debug.Assert(null != selectedMethod);
+ return selectedMethod!;
}
///
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/ObjectMethods.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/ObjectMethods.cs
deleted file mode 100644
index 239b659..0000000
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/ObjectMethods.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-using System.Reflection;
-using Unity.Interception.Utilities;
-
-namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration
-{
- internal static class ObjectMethods
- {
- // Zero argument constructor
- internal static ConstructorInfo Constructor { get { return StaticReflection.GetConstructorInfo(() => new object()); } }
- }
-}
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/VirtualMethodInvocationMethods.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/VirtualMethodInvocationMethods.cs
deleted file mode 100644
index 0243025..0000000
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/InterceptingClassGeneration/VirtualMethodInvocationMethods.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-
-
-using System.Reflection;
-using Unity.Interception.Utilities;
-
-namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration
-{
- internal static class VirtualMethodInvocationMethods
- {
- internal static ConstructorInfo VirtualMethodInvocation
- {
- get
- {
- return StaticReflection.GetConstructorInfo(
- () => new VirtualMethodInvocation(default(object), default(MethodBase)));
- }
- }
- }
-}
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/VirtualMethodInterceptor.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/VirtualMethodInterceptor.cs
index 16bc3a2..caea26f 100644
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/VirtualMethodInterceptor.cs
+++ b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/VirtualMethodInterceptor.cs
@@ -1,12 +1,9 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration;
using Unity.Interception.Properties;
-using Unity.Interception.Utilities;
namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception
{
@@ -26,7 +23,8 @@ public class VirtualMethodInterceptor : ITypeInterceptor
/// True if interception is possible, false if not.
public bool CanIntercept(Type t)
{
- Guard.ArgumentNotNull(t, "t");
+ if (null == t) throw new ArgumentNullException(nameof(t));
+
return t.IsClass &&
(t.IsPublic || t.IsNestedPublic) &&
t.IsVisible &&
@@ -42,14 +40,14 @@ public bool CanIntercept(Type t)
/// Sequence of objects.
public IEnumerable GetInterceptableMethods(Type interceptedType, Type implementationType)
{
- Guard.ArgumentNotNull(implementationType, "implementationType");
+ if (null == implementationType) throw new ArgumentNullException(nameof(implementationType));
return DoGetInterceptableMethods(implementationType);
}
private IEnumerable DoGetInterceptableMethods(Type implementationType)
{
- var interceptableMethodsToInterfaceMap = new Dictionary();
+ var interceptableMethodsToInterfaceMap = new Dictionary();
foreach (MethodInfo method in
implementationType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
@@ -87,8 +85,8 @@ private IEnumerable DoGetInterceptableMethods(Type imp
/// original type t, and supports interception.
public Type CreateProxyType(Type t, params Type[] additionalInterfaces)
{
- Guard.ArgumentNotNull(t, "t");
- Guard.ArgumentNotNull(additionalInterfaces, "additionalInterfaces");
+ if (null == t) throw new ArgumentNullException(nameof(t));
+ if (null == additionalInterfaces) throw new ArgumentNullException(nameof(additionalInterfaces));
if (!CanIntercept(t))
{
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/VirtualMethodInvocation.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/VirtualMethodInvocation.cs
index d8e6d2d..695b168 100644
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/VirtualMethodInvocation.cs
+++ b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/VirtualMethodInvocation.cs
@@ -1,11 +1,7 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
-using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Unity.Interception.PolicyInjection.Pipeline;
-using Unity.Interception.Utilities;
namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception
{
@@ -19,6 +15,8 @@ public class VirtualMethodInvocation : IMethodInvocation
private readonly ParameterCollection _arguments;
private readonly Dictionary _context;
+ internal static readonly ConstructorInfo ConstructorInfo = typeof(VirtualMethodInvocation).GetConstructor(new Type[] { typeof(object), typeof(MethodBase), typeof(object[]) });
+
///
/// Construct a new instance for the
/// given target object and method, passing the
@@ -27,14 +25,10 @@ public class VirtualMethodInvocation : IMethodInvocation
/// Object that is target of this invocation.
/// Method on to call.
/// Values for the parameters.
- [SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods",
- Justification = "Validation done by Guard class")]
public VirtualMethodInvocation(object target, MethodBase targetMethod, params object[] parameterValues)
{
- Guard.ArgumentNotNull(targetMethod, "targetMethod");
-
Target = target;
- MethodBase = targetMethod;
+ MethodBase = targetMethod ?? throw new ArgumentNullException(nameof(targetMethod));
_context = new Dictionary();
ParameterInfo[] targetParameters = targetMethod.GetParameters();
diff --git a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/VirtualMethodReturn.cs b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/VirtualMethodReturn.cs
index c0d8f46..2d87083 100644
--- a/src/Interceptors/TypeInterceptors/VirtualMethodInterception/VirtualMethodReturn.cs
+++ b/src/Interceptors/TypeInterceptors/VirtualMethodInterception/VirtualMethodReturn.cs
@@ -1,10 +1,7 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using System.Reflection;
using Unity.Interception.PolicyInjection.Pipeline;
-using Unity.Interception.Utilities;
namespace Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception
{
@@ -25,7 +22,7 @@ public class VirtualMethodReturn : IMethodReturn
/// All arguments (including current values) passed to the method.
public VirtualMethodReturn(IMethodInvocation originalInvocation, object returnValue, object[] arguments)
{
- Guard.ArgumentNotNull(originalInvocation, "originalInvocation");
+ if (null == originalInvocation) throw new ArgumentNullException(nameof(originalInvocation));
InvocationContext = originalInvocation.InvocationContext;
ReturnValue = returnValue;
@@ -40,8 +37,8 @@ public VirtualMethodReturn(IMethodInvocation originalInvocation, object returnVa
/// Exception that was thrown.
public VirtualMethodReturn(IMethodInvocation originalInvocation, Exception exception)
{
- Guard.ArgumentNotNull(originalInvocation, "originalInvocation");
-
+ if (null == originalInvocation) throw new ArgumentNullException(nameof(originalInvocation));
+
InvocationContext = originalInvocation.InvocationContext;
Exception = exception;
_outputs = new ParameterCollection(new object[0], new ParameterInfo[0], delegate { return false; });
@@ -57,12 +54,12 @@ public VirtualMethodReturn(IMethodInvocation originalInvocation, Exception excep
/// Returns value from the method call.
///
/// This value is null if the method has no return value.
- public object ReturnValue { get; set; }
+ public object? ReturnValue { get; set; }
///
/// If the method threw an exception, the exception object is here.
///
- public Exception Exception { get; set; }
+ public Exception? Exception { get; set; }
///
/// Retrieves a dictionary that can be used to store arbitrary additional
diff --git a/src/PolicyInjection/HandlerPipelineKey.cs b/src/PolicyInjection/HandlerPipelineKey.cs
index c8e5a80..8f2d061 100644
--- a/src/PolicyInjection/HandlerPipelineKey.cs
+++ b/src/PolicyInjection/HandlerPipelineKey.cs
@@ -1,8 +1,5 @@
-
-
-using System;
+using System;
using System.Reflection;
-using Unity.Interception.Utilities;
namespace Unity.Interception.PolicyInjection
{
@@ -21,7 +18,7 @@ public struct HandlerPipelineKey : IEquatable
/// The new key.
public static HandlerPipelineKey ForMethod(MethodBase methodBase)
{
- Guard.ArgumentNotNull(methodBase, "methodBase");
+ if (null == methodBase) throw new ArgumentNullException(nameof(methodBase));
return new HandlerPipelineKey(methodBase.DeclaringType.Module, methodBase.MetadataToken);
}
diff --git a/src/PolicyInjection/MatchingRules/ApplyNoPoliciesMatchingRule.cs b/src/PolicyInjection/MatchingRules/ApplyNoPoliciesMatchingRule.cs
index 3ba5074..cc67182 100644
--- a/src/PolicyInjection/MatchingRules/ApplyNoPoliciesMatchingRule.cs
+++ b/src/PolicyInjection/MatchingRules/ApplyNoPoliciesMatchingRule.cs
@@ -1,8 +1,6 @@
-
-
+using System;
using System.Reflection;
using Unity.Interception.PolicyInjection.Policies;
-using Unity.Interception.Utilities;
namespace Unity.Interception.PolicyInjection.MatchingRules
{
@@ -21,7 +19,7 @@ internal class ApplyNoPoliciesMatchingRule : IMatchingRule
/// True if the rule matches, false if it doesn't.
public bool Matches(MethodBase member)
{
- Guard.ArgumentNotNull(member, "member");
+ if (null == member) throw new ArgumentNullException(nameof(member));
bool hasNoPoliciesAttribute =
(member.GetCustomAttributes(typeof(ApplyNoPoliciesAttribute), false).Length != 0);
diff --git a/src/PolicyInjection/MatchingRules/AssemblyMatchingRule.cs b/src/PolicyInjection/MatchingRules/AssemblyMatchingRule.cs
index c0775db..7ab7788 100644
--- a/src/PolicyInjection/MatchingRules/AssemblyMatchingRule.cs
+++ b/src/PolicyInjection/MatchingRules/AssemblyMatchingRule.cs
@@ -1,9 +1,6 @@
-
-
-using System;
+using System;
using System.Globalization;
using System.Reflection;
-using Unity.Interception.Utilities;
namespace Unity.Interception.PolicyInjection.MatchingRules
{
@@ -31,12 +28,8 @@ public AssemblyMatchingRule(string assemblyName)
///
/// Assembly to match.
public AssemblyMatchingRule(Assembly assembly)
- : this((assembly != null) ? assembly.FullName : null)
+ : this((assembly ?? throw new ArgumentNullException(nameof(assembly))).FullName)
{
- if (assembly == null)
- {
- throw new ArgumentNullException(nameof(assembly));
- }
}
///
@@ -52,7 +45,7 @@ public AssemblyMatchingRule(Assembly assembly)
/// true if is in a matching assembly, false if not.
public bool Matches(MethodBase member)
{
- Guard.ArgumentNotNull(member, "member");
+ if (null == member) throw new ArgumentNullException(nameof(member));
if (member.DeclaringType == null)
{
@@ -66,7 +59,7 @@ public bool Matches(MethodBase member)
private static bool DoesAssemblyNameMatchString(string assemblyNameString, AssemblyName assemblyName)
{
- AssemblyName assemblyNameToMatch = null;
+ AssemblyName? assemblyNameToMatch;
try
{
assemblyNameToMatch = new AssemblyName(assemblyNameString);
diff --git a/src/PolicyInjection/MatchingRules/CustomAttributeMatchingRule.cs b/src/PolicyInjection/MatchingRules/CustomAttributeMatchingRule.cs
index 2958e61..ddad250 100644
--- a/src/PolicyInjection/MatchingRules/CustomAttributeMatchingRule.cs
+++ b/src/PolicyInjection/MatchingRules/CustomAttributeMatchingRule.cs
@@ -1,9 +1,6 @@
-
-
-using System;
+using System;
using System.Reflection;
using Unity.Interception.Properties;
-using Unity.Interception.Utilities;
namespace Unity.Interception.PolicyInjection.MatchingRules
{
@@ -23,7 +20,8 @@ public class CustomAttributeMatchingRule : IMatchingRule
/// If true, checks the base class for attributes as well.
public CustomAttributeMatchingRule(Type attributeType, bool inherited)
{
- Guard.ArgumentNotNull(attributeType, "attributeType");
+ if (null == attributeType) throw new ArgumentNullException(nameof(attributeType));
+
if (!attributeType.IsSubclassOf(typeof(Attribute)))
{
throw new ArgumentException(Resources.ExceptionAttributeNoSubclassOfAttribute, nameof(attributeType));
@@ -40,7 +38,7 @@ public CustomAttributeMatchingRule(Type attributeType, bool inherited)
/// true if it matches, false if not.
public bool Matches(MethodBase member)
{
- Guard.ArgumentNotNull(member, "member");
+ if (null == member) throw new ArgumentNullException(nameof(member));
object[] attribues = member.GetCustomAttributes(_attributeType, _inherited);
diff --git a/src/PolicyInjection/MatchingRules/MemberNameMatchingRule.cs b/src/PolicyInjection/MatchingRules/MemberNameMatchingRule.cs
index cd250b0..841c0ef 100644
--- a/src/PolicyInjection/MatchingRules/MemberNameMatchingRule.cs
+++ b/src/PolicyInjection/MatchingRules/MemberNameMatchingRule.cs
@@ -1,5 +1,4 @@
-
-
+using System;
using System.Collections.Generic;
using System.Reflection;
using Unity.Interception.Utilities;
@@ -32,8 +31,10 @@ public MemberNameMatchingRule(string nameToMatch)
/// If false, name comparisons are case sensitive. If true, name comparisons are case insensitive.
public MemberNameMatchingRule(string nameToMatch, bool ignoreCase)
{
- _patterns = new List();
- _patterns.Add(new Glob(nameToMatch, !ignoreCase));
+ _patterns = new List
+ {
+ new Glob(nameToMatch, !ignoreCase)
+ };
}
///
@@ -54,7 +55,7 @@ public MemberNameMatchingRule(IEnumerable namesToMatch)
/// If false, name comparisons are case sensitive. If true, name comparisons are case insensitive.
public MemberNameMatchingRule(IEnumerable namesToMatch, bool ignoreCase)
{
- Guard.ArgumentNotNull(namesToMatch, "namesToMatch");
+ if (null == namesToMatch) throw new ArgumentNullException(nameof(namesToMatch));
_patterns = new List();
foreach (string name in namesToMatch)
@@ -71,7 +72,7 @@ public MemberNameMatchingRule(IEnumerable namesToMatch, bool ignoreCase)
/// the pattern to match and case sensitivity flag.
public MemberNameMatchingRule(IEnumerable matches)
{
- Guard.ArgumentNotNull(matches, "matches");
+ if (null == matches) throw new ArgumentNullException(nameof(matches));
_patterns = new List();
foreach (MatchingInfo match in matches)
diff --git a/src/PolicyInjection/MatchingRules/MethodSignatureMatchingRule.cs b/src/PolicyInjection/MatchingRules/MethodSignatureMatchingRule.cs
index cfbb4f5..bf6398f 100644
--- a/src/PolicyInjection/MatchingRules/MethodSignatureMatchingRule.cs
+++ b/src/PolicyInjection/MatchingRules/MethodSignatureMatchingRule.cs
@@ -1,5 +1,4 @@
-
-
+using System;
using System.Collections.Generic;
using System.Reflection;
using Unity.Interception.Utilities;
@@ -23,7 +22,7 @@ public class MethodSignatureMatchingRule : IMatchingRule
/// If false, name comparisons are case sensitive. If true, name comparisons are case insensitive.
public MethodSignatureMatchingRule(string methodName, IEnumerable parameterTypeNames, bool ignoreCase)
{
- Guard.ArgumentNotNull(parameterTypeNames, "parameterTypeNames");
+ if (null == parameterTypeNames) throw new ArgumentNullException(nameof(parameterTypeNames));
_methodNamePattern = new Glob(methodName, !ignoreCase);
_parameterRules = new List();
@@ -75,7 +74,7 @@ public MethodSignatureMatchingRule(IEnumerable parameterTypeNames, bool
/// True if match, false if not.
public bool Matches(MethodBase member)
{
- Guard.ArgumentNotNull(member, "member");
+ if (null == member) throw new ArgumentNullException(nameof(member));
if (!_methodNamePattern.IsMatch(member.Name))
{
diff --git a/src/PolicyInjection/MatchingRules/NamespaceMatchingRule.cs b/src/PolicyInjection/MatchingRules/NamespaceMatchingRule.cs
index 28eb2ca..5a90af7 100644
--- a/src/PolicyInjection/MatchingRules/NamespaceMatchingRule.cs
+++ b/src/PolicyInjection/MatchingRules/NamespaceMatchingRule.cs
@@ -1,9 +1,6 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using System.Reflection;
-using Unity.Interception.Utilities;
namespace Unity.Interception.PolicyInjection.MatchingRules
{
@@ -44,7 +41,7 @@ public NamespaceMatchingRule(string namespaceName, bool ignoreCase)
/// Collection of namespace names to match.
public NamespaceMatchingRule(IEnumerable matches)
{
- Guard.ArgumentNotNull(matches, "matches");
+ if (null == matches) throw new ArgumentNullException(nameof(matches));
_matches = new List();
foreach (MatchingInfo match in matches)
@@ -72,7 +69,7 @@ public bool Matches(MethodBase member)
///
private class NamespaceMatchingInfo : MatchingInfo
{
- private bool wildCard;
+ private readonly bool wildCard;
private const string WildCardString = ".*";
///
diff --git a/src/PolicyInjection/MatchingRules/ParameterTypeMatchingRule.cs b/src/PolicyInjection/MatchingRules/ParameterTypeMatchingRule.cs
index d1d0f2b..9fc04ea 100644
--- a/src/PolicyInjection/MatchingRules/ParameterTypeMatchingRule.cs
+++ b/src/PolicyInjection/MatchingRules/ParameterTypeMatchingRule.cs
@@ -1,8 +1,6 @@
-
-
+using System;
using System.Collections.Generic;
using System.Reflection;
-using Unity.Interception.Utilities;
namespace Unity.Interception.PolicyInjection.MatchingRules
{
@@ -38,7 +36,7 @@ public ParameterTypeMatchingRule(IEnumerable matches)
/// true if member matches, false if it doesn't.
public bool Matches(MethodBase member)
{
- Guard.ArgumentNotNull(member, "member");
+ if (null == member) throw new ArgumentNullException(nameof(member));
ParameterInfo[] parametersInfo = member.GetParameters();
@@ -78,7 +76,7 @@ public bool Matches(MethodBase member)
}
if (matchInfo.Kind == ParameterKind.ReturnValue)
{
- MethodInfo method = member as MethodInfo;
+ MethodInfo? method = member as MethodInfo;
if (method != null)
{
if (typeRule.Matches(method.ReturnType))
diff --git a/src/PolicyInjection/MatchingRules/PropertyMatchingRule.cs b/src/PolicyInjection/MatchingRules/PropertyMatchingRule.cs
index f040f3b..24d7f68 100644
--- a/src/PolicyInjection/MatchingRules/PropertyMatchingRule.cs
+++ b/src/PolicyInjection/MatchingRules/PropertyMatchingRule.cs
@@ -1,5 +1,4 @@
-
-
+using System;
using System.Collections.Generic;
using System.Reflection;
using Unity.Interception.Utilities;
@@ -55,7 +54,7 @@ public PropertyMatchingRule(string propertyName, PropertyMatchingOption option,
/// properties to match.
public PropertyMatchingRule(IEnumerable matches)
{
- Guard.ArgumentNotNull(matches, "matches");
+ if (null == matches) throw new ArgumentNullException(nameof(matches));
foreach (PropertyMatchingInfo match in matches)
{
@@ -78,7 +77,7 @@ public PropertyMatchingRule(IEnumerable matches)
/// True if it matches, false if it does not.
public bool Matches(MethodBase member)
{
- Guard.ArgumentNotNull(member, "member");
+ if (null == member) throw new ArgumentNullException(nameof(member));
return
member.IsSpecialName &&
diff --git a/src/PolicyInjection/MatchingRules/ReturnTypeMatchingRule.cs b/src/PolicyInjection/MatchingRules/ReturnTypeMatchingRule.cs
index d40b6d5..7a84609 100644
--- a/src/PolicyInjection/MatchingRules/ReturnTypeMatchingRule.cs
+++ b/src/PolicyInjection/MatchingRules/ReturnTypeMatchingRule.cs
@@ -60,7 +60,7 @@ public ReturnTypeMatchingRule(string returnTypeName, bool ignoreCase)
/// true if return types match, false if they don't.
public bool Matches(MethodBase member)
{
- MethodInfo method = member as MethodInfo;
+ MethodInfo? method = member as MethodInfo;
if (method == null)
{
return false;
diff --git a/src/PolicyInjection/MatchingRules/TypeMatchingRule.cs b/src/PolicyInjection/MatchingRules/TypeMatchingRule.cs
index 417f2c3..7737c37 100644
--- a/src/PolicyInjection/MatchingRules/TypeMatchingRule.cs
+++ b/src/PolicyInjection/MatchingRules/TypeMatchingRule.cs
@@ -1,9 +1,6 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using System.Reflection;
-using Unity.Interception.Utilities;
namespace Unity.Interception.PolicyInjection.MatchingRules
{
@@ -67,7 +64,7 @@ public TypeMatchingRule(IEnumerable matches)
/// True if match, false if not.
public bool Matches(MethodBase member)
{
- Guard.ArgumentNotNull(member, "member");
+ if (null == member) throw new ArgumentNullException(nameof(member));
if (member.DeclaringType == null)
{
@@ -85,7 +82,7 @@ public bool Matches(MethodBase member)
/// True if it matches, false if it doesn't.
public bool Matches(Type t)
{
- Guard.ArgumentNotNull(t, "t");
+ if (null == t) throw new ArgumentNullException(nameof(t));
foreach (MatchingInfo match in _matches)
{
@@ -108,7 +105,7 @@ private static StringComparison Comparison(bool ignoreCase)
private static string SafeGetTypeName(Type type)
{
- Guard.ArgumentNotNull(type, "type");
+ if (null == type) throw new ArgumentNullException(nameof(type));
return type.Name;
}
}
diff --git a/src/PolicyInjection/Pipeline/ICallHandler.cs b/src/PolicyInjection/Pipeline/ICallHandler.cs
index c1ac477..c6a1d37 100644
--- a/src/PolicyInjection/Pipeline/ICallHandler.cs
+++ b/src/PolicyInjection/Pipeline/ICallHandler.cs
@@ -15,7 +15,7 @@ public interface ICallHandler
/// Delegate to execute to get the next delegate in the handler
/// chain.
/// Return value from the target.
- IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext);
+ IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate? getNext);
///
/// Order in which the handler will be executed
@@ -30,7 +30,7 @@ public interface ICallHandler
/// Inputs to the current method call.
/// Delegate to get the next handler in the chain.
/// Return from the next method in the chain.
- public delegate IMethodReturn InvokeHandlerDelegate(IMethodInvocation input, GetNextHandlerDelegate getNext);
+ public delegate IMethodReturn InvokeHandlerDelegate(IMethodInvocation input, GetNextHandlerDelegate? getNext);
///
/// This delegate type is passed to each handler's Invoke method.
diff --git a/src/PolicyInjection/Pipeline/IMethodReturn.cs b/src/PolicyInjection/Pipeline/IMethodReturn.cs
index 7957633..e61a78b 100644
--- a/src/PolicyInjection/Pipeline/IMethodReturn.cs
+++ b/src/PolicyInjection/Pipeline/IMethodReturn.cs
@@ -23,12 +23,12 @@ public interface IMethodReturn
/// Returns value from the method call.
///
/// This value is null if the method has no return value.
- object ReturnValue { get; set; }
+ object? ReturnValue { get; set; }
///
/// If the method threw an exception, the exception object is here.
///
- Exception Exception { get; set; }
+ Exception? Exception { get; set; }
///
/// Retrieves a dictionary that can be used to store arbitrary additional
diff --git a/src/PolicyInjection/Pipeline/ParameterCollection.cs b/src/PolicyInjection/Pipeline/ParameterCollection.cs
index 40a5810..a60c9d6 100644
--- a/src/PolicyInjection/Pipeline/ParameterCollection.cs
+++ b/src/PolicyInjection/Pipeline/ParameterCollection.cs
@@ -1,11 +1,8 @@
-
-
-using System;
+using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
-using Unity.Interception.Utilities;
namespace Unity.Interception.PolicyInjection.Pipeline
{
@@ -53,10 +50,9 @@ public ArgumentInfo(int index, ParameterInfo parameterInfo)
/// parameters, for example.
public ParameterCollection(object[] arguments, ParameterInfo[] argumentInfo, Predicate isArgumentPartOfCollection)
{
- Guard.ArgumentNotNull(arguments, "arguments");
- Guard.ArgumentNotNull(isArgumentPartOfCollection, "isArgumentPartOfCollection");
+ if (null == isArgumentPartOfCollection) throw new ArgumentNullException(nameof(isArgumentPartOfCollection));
- _arguments = arguments;
+ _arguments = arguments ?? throw new ArgumentNullException(nameof(arguments));
_argumentInfo = new List();
for (int argumentNumber = 0; argumentNumber < argumentInfo.Length; ++argumentNumber)
{
diff --git a/src/PolicyInjection/Pipeline/PipelineManager.cs b/src/PolicyInjection/Pipeline/PipelineManager.cs
index a253201..16f1866 100644
--- a/src/PolicyInjection/Pipeline/PipelineManager.cs
+++ b/src/PolicyInjection/Pipeline/PipelineManager.cs
@@ -1,10 +1,8 @@
-
-
+using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using Unity.Interception.Interceptors;
-using Unity.Interception.Utilities;
namespace Unity.Interception.PolicyInjection.Pipeline
{
@@ -59,8 +57,6 @@ public void SetPipeline(MethodBase method, HandlerPipeline pipeline)
/// True if the pipeline has any handlers in it, false if not.
public bool InitializePipeline(MethodImplementationInfo method, IEnumerable handlers)
{
- Guard.ArgumentNotNull(method, "method");
-
var pipeline = CreatePipeline(method.ImplementationMethodInfo, handlers);
if (method.InterfaceMethodInfo != null)
{
@@ -72,7 +68,7 @@ public bool InitializePipeline(MethodImplementationInfo method, IEnumerable handlers)
{
- HandlerPipelineKey key = HandlerPipelineKey.ForMethod(method);
+ var key = HandlerPipelineKey.ForMethod(method);
if (_pipelines.ContainsKey(key))
{
return _pipelines[key];
diff --git a/src/PolicyInjection/Policies/AttributeDrivenPolicy.cs b/src/PolicyInjection/Policies/AttributeDrivenPolicy.cs
index 2da6505..315bb59 100644
--- a/src/PolicyInjection/Policies/AttributeDrivenPolicy.cs
+++ b/src/PolicyInjection/Policies/AttributeDrivenPolicy.cs
@@ -1,5 +1,4 @@
-
-
+using System;
using System.Collections.Generic;
using Unity.Interception.Interceptors;
using Unity.Interception.PolicyInjection.MatchingRules;
@@ -33,8 +32,6 @@ public AttributeDrivenPolicy()
/// true if policy applies to this member, false if not.
protected override bool DoesMatch(MethodImplementationInfo member)
{
- Guard.ArgumentNotNull(member, "member");
-
bool matchesInterface = member.InterfaceMethodInfo != null ? _attributeMatchRule.Matches(member.InterfaceMethodInfo) : false;
bool matchesImplementation = _attributeMatchRule.Matches(member.ImplementationMethodInfo);
diff --git a/src/PolicyInjection/Policies/InjectionPolicy.cs b/src/PolicyInjection/Policies/InjectionPolicy.cs
index 3b40404..9e3ab71 100644
--- a/src/PolicyInjection/Policies/InjectionPolicy.cs
+++ b/src/PolicyInjection/Policies/InjectionPolicy.cs
@@ -1,12 +1,9 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using System.Reflection;
using Unity.Interception.Interceptors;
using Unity.Interception.PolicyInjection.MatchingRules;
using Unity.Interception.PolicyInjection.Pipeline;
-using Unity.Interception.Utilities;
namespace Unity.Interception.PolicyInjection.Policies
{
@@ -100,7 +97,7 @@ public virtual IEnumerable GetHandlersFor(MethodImplementationInfo
/// The set of methods
protected static IEnumerable GetMethodSet(MethodBase member)
{
- Guard.ArgumentNotNull(member, "member");
+ if (null == member) throw new ArgumentNullException(nameof(member));
List methodSet = new List(new[] { member });
if (member.DeclaringType != null && !member.DeclaringType.IsInterface)
diff --git a/src/PolicyInjection/Policies/RuleDrivenPolicy.cs b/src/PolicyInjection/Policies/RuleDrivenPolicy.cs
index 0131258..f75dbec 100644
--- a/src/PolicyInjection/Policies/RuleDrivenPolicy.cs
+++ b/src/PolicyInjection/Policies/RuleDrivenPolicy.cs
@@ -1,10 +1,8 @@
-
-
+using System;
using System.Collections.Generic;
using Unity.Interception.Interceptors;
using Unity.Interception.PolicyInjection.MatchingRules;
using Unity.Interception.PolicyInjection.Pipeline;
-using Unity.Interception.Utilities;
namespace Unity.Interception.PolicyInjection.Policies
{
@@ -47,8 +45,6 @@ public RuleDrivenPolicy(string name, IMatchingRule[] matchingRules, string[] cal
/// true if ruleset matches, false if it does not.
protected override bool DoesMatch(MethodImplementationInfo member)
{
- Guard.ArgumentNotNull(member, "member");
-
bool matchesInterface = member.InterfaceMethodInfo != null ? _ruleSet.Matches(member.InterfaceMethodInfo) : false;
bool matchesImplementation = _ruleSet.Matches(member.ImplementationMethodInfo);
return matchesInterface | matchesImplementation;
diff --git a/src/PolicyInjection/PolicyInjectionBehavior.cs b/src/PolicyInjection/PolicyInjectionBehavior.cs
index 1baceb3..0077bd2 100644
--- a/src/PolicyInjection/PolicyInjectionBehavior.cs
+++ b/src/PolicyInjection/PolicyInjectionBehavior.cs
@@ -1,13 +1,11 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Reflection;
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.Interceptors;
using Unity.Interception.PolicyInjection.Pipeline;
using Unity.Interception.PolicyInjection.Policies;
-using Unity.Interception.Utilities;
namespace Unity.Interception.PolicyInjection
{
@@ -16,7 +14,7 @@ namespace Unity.Interception.PolicyInjection
///
public class PolicyInjectionBehavior : IInterceptionBehavior
{
- private readonly PipelineManager _pipelineManager;
+ private readonly PipelineManager? _pipelineManager;
///
/// Initializes a new instance of the with a pipeline manager.
@@ -38,7 +36,7 @@ public PolicyInjectionBehavior(PipelineManager pipelineManager)
public PolicyInjectionBehavior(CurrentInterceptionRequest interceptionRequest, InjectionPolicy[] policies,
IUnityContainer container)
{
- Guard.ArgumentNotNull(interceptionRequest, "interceptionRequest");
+ if (null == interceptionRequest) throw new ArgumentNullException(nameof(interceptionRequest));
var allPolicies = new PolicySet(policies);
bool hasHandlers = false;
@@ -63,20 +61,17 @@ public PolicyInjectionBehavior(CurrentInterceptionRequest interceptionRequest, I
/// Delegate to execute to get the next delegate in the handler
/// chain.
/// Return value from the target.
- public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
+ public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate? getNext)
{
- Guard.ArgumentNotNull(input, "input");
- Guard.ArgumentNotNull(getNext, "getNext");
-
- HandlerPipeline pipeline = GetPipeline(input.MethodBase);
+ HandlerPipeline pipeline = GetPipeline((input ?? throw new ArgumentNullException(nameof(input))).MethodBase);
return pipeline.Invoke(
input,
- delegate(IMethodInvocation policyInjectionInput, GetNextHandlerDelegate policyInjectionInputGetNext)
+ delegate(IMethodInvocation policyInjectionInput, GetNextHandlerDelegate? policyInjectionInputGetNext)
{
try
{
- return getNext()(policyInjectionInput, getNext);
+ return (getNext ?? throw new ArgumentNullException(nameof(getNext)))()(policyInjectionInput, getNext);
}
catch (TargetInvocationException ex)
{
@@ -89,7 +84,8 @@ public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehavior
private HandlerPipeline GetPipeline(MethodBase method)
{
- return _pipelineManager.GetPipeline(method);
+ Debug.Assert(null != _pipelineManager);
+ return _pipelineManager!.GetPipeline(method);
}
///
diff --git a/src/Properties/Resources.Designer.cs b/src/Properties/Resources.Designer.cs
index 550feff..730b9ad 100644
--- a/src/Properties/Resources.Designer.cs
+++ b/src/Properties/Resources.Designer.cs
@@ -28,7 +28,6 @@ internal class Resources {
private static global::System.Globalization.CultureInfo resourceCulture;
- [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
diff --git a/src/Strategies/InstanceInterceptionStrategy.cs b/src/Strategies/InstanceInterceptionStrategy.cs
index 19afc61..1ba11ad 100644
--- a/src/Strategies/InstanceInterceptionStrategy.cs
+++ b/src/Strategies/InstanceInterceptionStrategy.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Linq;
using Unity.Builder;
using Unity.Interception.InterceptionBehaviors;
@@ -23,38 +24,32 @@ public class InstanceInterceptionStrategy : BuilderStrategy
public override void PostBuildUp(ref BuilderContext context)
{
// If it's already been intercepted, don't do it again.
- if (context.Existing is IInterceptingProxy)
- {
- return;
- }
+ if (context.Existing is IInterceptingProxy) return;
- IInstanceInterceptionPolicy interceptionPolicy =
+ IInstanceInterceptionPolicy? interceptionPolicy =
FindInterceptionPolicy(ref context, true);
- if (interceptionPolicy == null)
- {
- return;
- }
+ if (interceptionPolicy == null) return;
var interceptor = interceptionPolicy.GetInterceptor(ref context);
+ if (null == interceptor) return;
- IInterceptionBehaviorsPolicy interceptionBehaviorsPolicy =
+ IInterceptionBehaviorsPolicy? interceptionBehaviorsPolicy =
FindInterceptionPolicy(ref context, true);
- if (interceptionBehaviorsPolicy == null)
- {
- return;
- }
+ if (null == interceptionBehaviorsPolicy) return;
- IAdditionalInterfacesPolicy additionalInterfacesPolicy =
+ IAdditionalInterfacesPolicy? additionalInterfacesPolicy =
FindInterceptionPolicy(ref context, false);
IEnumerable additionalInterfaces =
additionalInterfacesPolicy != null ? additionalInterfacesPolicy.AdditionalInterfaces : Type.EmptyTypes;
+ Debug.Assert(null != context.Existing);
+
Type typeToIntercept = context.RegistrationType;
- Type implementationType = context.Existing.GetType();
+ Type implementationType = context.Existing!.GetType();
IInterceptionBehavior[] interceptionBehaviors =
interceptionBehaviorsPolicy.GetEffectiveBehaviors(
- ref context, interceptor, typeToIntercept, implementationType)
+ ref context, interceptor!, typeToIntercept, implementationType)
.ToArray();
if (interceptionBehaviors.Length > 0)
@@ -62,14 +57,14 @@ public override void PostBuildUp(ref BuilderContext context)
context.Existing =
Intercept.ThroughProxyWithAdditionalInterfaces(
typeToIntercept,
- context.Existing,
- interceptor,
+ context.Existing!,
+ interceptor!,
interceptionBehaviors,
additionalInterfaces);
}
}
- private static T FindInterceptionPolicy(ref BuilderContext context, bool probeOriginalKey)
+ private static T? FindInterceptionPolicy(ref BuilderContext context, bool probeOriginalKey)
where T : class
{
// First, try for an original build key
@@ -85,12 +80,13 @@ private static T FindInterceptionPolicy(ref BuilderContext context, bool prob
return policy;
}
- public static TPolicyInterface GetPolicyOrDefault(ref BuilderContext context)
+ public static TPolicyInterface? GetPolicyOrDefault(ref BuilderContext context)
+ where TPolicyInterface : class
{
- return (TPolicyInterface)(GetNamedPolicy(ref context, context.RegistrationType, context.Name) ??
+ return (TPolicyInterface?)(GetNamedPolicy(ref context, context.RegistrationType, context.Name) ??
GetNamedPolicy(ref context, context.RegistrationType, UnityContainer.All));
- object GetNamedPolicy(ref BuilderContext c, Type t, string n)
+ static object? GetNamedPolicy(ref BuilderContext c, Type t, string? n)
{
return (c.Get(t, n, typeof(TPolicyInterface)) ?? (
#if NETCOREAPP1_0 || NETSTANDARD1_0
diff --git a/src/Strategies/TypeInterceptionStrategy.cs b/src/Strategies/TypeInterceptionStrategy.cs
index 0800e75..3f86322 100644
--- a/src/Strategies/TypeInterceptionStrategy.cs
+++ b/src/Strategies/TypeInterceptionStrategy.cs
@@ -1,13 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Reflection;
using Unity.Builder;
-using Unity.Injection;
-using Unity.Interception.ContainerIntegration.Selection;
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.Interceptors;
-using Unity.Policy;
using Unity.Strategies;
namespace Unity.Interception.ContainerIntegration.ObjectBuilder
@@ -62,7 +58,7 @@ public override void PreBuildUp(ref BuilderContext context)
ref context, interceptor, typeToBuild, typeToBuild)
.Where(ib => ib.WillExecute);
- IAdditionalInterfacesPolicy additionalInterfacesPolicy =
+ IAdditionalInterfacesPolicy? additionalInterfacesPolicy =
GetPolicyOrDefault(ref context);
IEnumerable additionalInterfaces =
@@ -75,10 +71,7 @@ public override void PreBuildUp(ref BuilderContext context)
Type[] allAdditionalInterfaces =
Intercept.GetAllAdditionalInterfaces(enumerable, additionalInterfaces);
- Type interceptingType =
- interceptor.CreateProxyType(typeToBuild, allAdditionalInterfaces);
-
- DerivedTypeConstructorSelectorPolicy.SetPolicyForInterceptingType(ref context, interceptingType);
+ context.Type = interceptor.CreateProxyType(typeToBuild, allAdditionalInterfaces);
}
///
@@ -91,14 +84,12 @@ public override void PreBuildUp(ref BuilderContext context)
/// Context of the build operation.
public override void PostBuildUp(ref BuilderContext context)
{
- IInterceptingProxy proxy = context.Existing as IInterceptingProxy;
-
- if (proxy == null)
+ if (!(context.Existing is IInterceptingProxy proxy))
{
return;
}
- var effectiveInterceptionBehaviorsPolicy = (EffectiveInterceptionBehaviorsPolicy)context.Registration.Get(
+ var effectiveInterceptionBehaviorsPolicy = (EffectiveInterceptionBehaviorsPolicy?)context.Registration.Get(
typeof(EffectiveInterceptionBehaviorsPolicy));
if (effectiveInterceptionBehaviorsPolicy == null)
@@ -112,12 +103,12 @@ public override void PostBuildUp(ref BuilderContext context)
}
}
- public static TPolicyInterface GetPolicyOrDefault(ref BuilderContext context)
+ public static TPolicyInterface? GetPolicyOrDefault(ref BuilderContext context) where TPolicyInterface : class
{
- return (TPolicyInterface)(GetNamedPolicy(ref context, context.RegistrationType, context.Name) ??
+ return (TPolicyInterface?)(GetNamedPolicy(ref context, context.RegistrationType, context.Name) ??
GetNamedPolicy(ref context, context.RegistrationType, UnityContainer.All));
- object GetNamedPolicy(ref BuilderContext c, Type t, string n)
+ static object? GetNamedPolicy(ref BuilderContext c, Type t, string? n)
{
return (c.Get(t, n, typeof(TPolicyInterface)) ?? (
#if NETCOREAPP1_0 || NETSTANDARD1_0
@@ -146,91 +137,6 @@ public EffectiveInterceptionBehaviorsPolicy()
public IEnumerable Behaviors { get; set; }
}
- private class DerivedTypeConstructorSelectorPolicy : ISelect
- {
- internal readonly Type InterceptingType;
- internal readonly ISelect OriginalConstructorSelectorPolicy;
-
- internal DerivedTypeConstructorSelectorPolicy(
- Type interceptingType,
- ISelect originalConstructorSelectorPolicy)
- {
- InterceptingType = interceptingType;
- OriginalConstructorSelectorPolicy = originalConstructorSelectorPolicy;
- }
-
-
- public IEnumerable
internal static class Guard
{
- ///
- /// Throws if the given argument is null.
- ///
- /// if tested value if null.
- /// Argument value to test.
- /// Name of the argument being tested.
- public static void ArgumentNotNull(object argumentValue,
- string argumentName)
- {
- if (argumentValue == null)
- {
- throw new ArgumentNullException(argumentName);
- }
- }
-
- ///
- /// Throws an exception if the tested string argument is null or the empty string.
- ///
- /// Thrown if string value is null.
- /// Thrown if the string is empty
- /// Argument value to check.
- /// Name of argument being checked.
- public static void ArgumentNotNullOrEmpty(string argumentValue,
- string argumentName)
- {
- if (argumentValue == null)
- {
- throw new ArgumentNullException(argumentName);
- }
-
- if (argumentValue.Length == 0)
- {
- throw new ArgumentException(@"The provided string argument must not be empty.", argumentName);
- }
- }
-
///
/// Verifies that an argument type is assignable from the provided type (meaning
/// interfaces are implemented, or classes exist in the base class hierarchy).
@@ -76,51 +38,5 @@ public static void TypeIsAssignable(Type assignmentTargetType, Type assignmentVa
argumentName);
}
}
-
- ///
- /// Verifies that an argument instance is assignable from the provided type (meaning
- /// interfaces are implemented, or classes exist in the base class hierarchy, or instance can be
- /// assigned through a runtime wrapper, as is the case for COM Objects).
- ///
- /// The argument type that will be assigned to.
- /// The instance that will be assigned.
- /// Argument name.
- public static void InstanceIsAssignable(Type assignmentTargetType, object assignmentInstance, string argumentName)
- {
- if (assignmentTargetType == null)
- {
- throw new ArgumentNullException(nameof(assignmentTargetType));
- }
-
- if (assignmentInstance == null)
- {
- throw new ArgumentNullException(nameof(assignmentInstance));
- }
-
- if (!assignmentTargetType.GetTypeInfo().IsAssignableFrom(assignmentInstance.GetType().GetTypeInfo()))
- {
- throw new ArgumentException(
- string.Format(
- CultureInfo.CurrentCulture,
- "The type {1} cannot be assigned to variables of type {0}.",
- assignmentTargetType,
- GetTypeName(assignmentInstance)),
- argumentName);
- }
- }
-
- private static string GetTypeName(object assignmentInstance)
- {
- string assignmentInstanceType;
- try
- {
- assignmentInstanceType = assignmentInstance.GetType().FullName;
- }
- catch (Exception)
- {
- assignmentInstanceType = "";
- }
- return assignmentInstanceType;
- }
}
}
diff --git a/src/Utilities/Pair.cs b/src/Utilities/Pair.cs
deleted file mode 100644
index 6d45248..0000000
--- a/src/Utilities/Pair.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-
-
-namespace Unity.Interception.Utilities
-{
- ///
- /// A helper class that encapsulates two different
- /// data items together into a a single item.
- ///
- public class Pair
- {
- ///
- /// Create a new containing
- /// the two values give.
- ///
- /// First value
- /// Second value
- public Pair(TFirst first, TSecond second)
- {
- First = first;
- Second = second;
- }
-
- ///
- /// The first value of the pair.
- ///
- public TFirst First { get; }
-
- ///
- /// The second value of the pair.
- ///
- public TSecond Second { get; }
- }
-
- ///
- /// Container for a Pair helper method.
- ///
- public static class Pair
- {
- ///
- /// A helper factory method that lets users take advantage of type inference.
- ///
- /// Type of first value.
- /// Type of second value.
- /// First value.
- /// Second value.
- /// A new instance.
- public static Pair Make(TFirstParameter first, TSecondParameter second)
- {
- return new Pair(first, second);
- }
- }
-}
diff --git a/src/Utilities/ReflectionHelper.cs b/src/Utilities/ReflectionHelper.cs
index 90a6cdf..45bff27 100644
--- a/src/Utilities/ReflectionHelper.cs
+++ b/src/Utilities/ReflectionHelper.cs
@@ -1,6 +1,4 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
@@ -13,36 +11,17 @@ namespace Unity.Interception.Utilities
///
public static class ReflectionHelper
{
- ///
- /// Given a MethodBase for a property's get or set method,
- /// return the corresponding property info.
- ///
- /// MethodBase for the property's get or set method.
- /// PropertyInfo for the property, or null if method is not part of a property.
- public static PropertyInfo GetPropertyFromMethod(MethodBase method)
- {
- Guard.ArgumentNotNull(method, "method");
-
- var methodInfo = method as MethodInfo;
- if (methodInfo != null)
- {
- return GetPropertyFromMethod(methodInfo);
- }
-
- return null;
- }
-
///
/// Given a MethodInfo for a property's get or set method,
/// return the corresponding property info.
///
/// MethodBase for the property's get or set method.
/// PropertyInfo for the property, or null if method is not part of a property.
- public static PropertyInfo GetPropertyFromMethod(MethodInfo method)
+ public static PropertyInfo? GetPropertyFromMethod(MethodInfo method)
{
- Guard.ArgumentNotNull(method, "method");
+ if (null == method) throw new ArgumentNullException(nameof(method));
- PropertyInfo property = null;
+ PropertyInfo? property = null;
if (method.IsSpecialName)
{
var containingType = method.DeclaringType;
@@ -53,10 +32,8 @@ public static PropertyInfo GetPropertyFromMethod(MethodInfo method)
if (isSetter || isGetter)
{
var propertyName = method.Name.Substring(4);
- Type propertyType;
- Type[] indexerTypes;
- GetPropertyTypes(method, isGetter, out propertyType, out indexerTypes);
+ GetPropertyTypes(method, isGetter, out Type propertyType, out Type[] indexerTypes);
property =
containingType.GetProperty(
@@ -69,6 +46,7 @@ public static PropertyInfo GetPropertyFromMethod(MethodInfo method)
}
}
}
+
return property;
}
@@ -103,7 +81,7 @@ private static void GetPropertyTypes(MethodInfo method, bool isGetter, out Type
/// Array of found attributes.
public static TAttribute[] GetAttributes(MemberInfo member, bool inherits) where TAttribute : Attribute
{
- Guard.ArgumentNotNull(member, "member");
+ if (null == member) throw new ArgumentNullException(nameof(member));
object[] attributesAsObjects = member.GetCustomAttributes(typeof(TAttribute), inherits);
TAttribute[] attributes = new TAttribute[attributesAsObjects.Length];
@@ -128,7 +106,7 @@ public static TAttribute[] GetAttributes(MemberInfo member, bool inh
public static TAttribute[] GetAllAttributes(MemberInfo member, bool inherits)
where TAttribute : Attribute
{
- Guard.ArgumentNotNull(member, "member");
+ if (null == member) throw new ArgumentNullException(nameof(member));
List attributes = new List();
@@ -136,10 +114,10 @@ public static TAttribute[] GetAllAttributes(MemberInfo member, bool
{
attributes.AddRange(GetAttributes(member.DeclaringType, inherits));
- MethodInfo methodInfo = member as MethodInfo;
+ MethodInfo? methodInfo = member as MethodInfo;
if (methodInfo != null)
{
- PropertyInfo prop = GetPropertyFromMethod(methodInfo);
+ PropertyInfo? prop = GetPropertyFromMethod(methodInfo);
if (prop != null)
{
attributes.AddRange(GetAttributes(prop, inherits));
@@ -149,21 +127,5 @@ public static TAttribute[] GetAllAttributes(MemberInfo member, bool
attributes.AddRange(GetAttributes(member, inherits));
return attributes.ToArray();
}
-
- public static readonly MethodInfo ExceptionDispatchInfoCaptureMethod;
-
- public static readonly MethodInfo ExceptionDispatchInfoThrowMethod;
-
- static ReflectionHelper()
- {
- Assembly mscorlib = typeof(int).Assembly;
- ExceptionDispatchInfoCaptureMethod = mscorlib
- ?.GetType("System.Runtime.ExceptionServices.ExceptionDispatchInfo")
- ?.GetMethod("Capture", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(Exception) }, null);
-
- ExceptionDispatchInfoThrowMethod = mscorlib
- ?.GetType("System.Runtime.ExceptionServices.ExceptionDispatchInfo")
- ?.GetMethod("Throw", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { }, null);
- }
}
}
diff --git a/src/Utilities/Sequence.cs b/src/Utilities/Sequence.cs
deleted file mode 100644
index cb39397..0000000
--- a/src/Utilities/Sequence.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-
-
-using System.Collections.Generic;
-
-namespace Unity.Interception.Utilities
-{
- ///
- /// A series of helper methods to deal with sequences -
- /// objects that implement .
- ///
- public static class Sequence
- {
- ///
- /// A function that turns an arbitrary parameter list into an
- /// .
- ///
- /// Type of arguments.
- /// The items to put into the collection.
- /// An array that contains the values of the .
- public static T[] Collect(params T[] arguments)
- {
- return arguments;
- }
-
- ///
- /// Given two sequences, return a new sequence containing the corresponding values
- /// from each one.
- ///
- /// Type of first sequence.
- /// Type of second sequence.
- /// First sequence of items.
- /// Second sequence of items.
- /// New sequence of pairs. This sequence ends when the shorter of sequence1 and sequence2 does.
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
- Justification = "No other way to do this")]
- public static IEnumerable> Zip(IEnumerable sequence1, IEnumerable sequence2)
- {
- var enum1 = sequence1.GetEnumerator();
- var enum2 = sequence2.GetEnumerator();
-
- while (enum1.MoveNext())
- {
- if (enum2.MoveNext())
- {
- yield return new Pair(enum1.Current, enum2.Current);
- }
- else
- {
- yield break;
- }
- }
- }
- }
-}
diff --git a/src/Utilities/StaticReflection.cs b/src/Utilities/StaticReflection.cs
deleted file mode 100644
index 8da2fe8..0000000
--- a/src/Utilities/StaticReflection.cs
+++ /dev/null
@@ -1,157 +0,0 @@
-
-
-using System;
-using System.Linq.Expressions;
-using System.Reflection;
-
-namespace Unity.Interception.Utilities
-{
- ///
- /// A set of helper methods to pick through lambdas and pull out
- /// from them.
- ///
- public static class StaticReflection
- {
- ///
- /// Pull out a object from an expression of the form
- /// () => SomeClass.SomeMethod()
- ///
- /// Expression describing the method to call.
- /// Corresponding .
- public static MethodInfo GetMethodInfo(Expression expression)
- {
- return GetMethodInfo((LambdaExpression)expression);
- }
-
- ///
- /// Pull out a object from an expression of the form
- /// x => x.SomeMethod()
- ///
- /// The type where the method is defined.
- /// Expression describing the method to call.
- /// Corresponding .
- public static MethodInfo GetMethodInfo(Expression> expression)
- {
- return GetMethodInfo((LambdaExpression)expression);
- }
-
- private static MethodInfo GetMethodInfo(LambdaExpression lambda)
- {
- GuardProperExpressionForm(lambda.Body);
-
- var call = (MethodCallExpression)lambda.Body;
- return call.Method;
- }
-
- ///
- /// Pull out a object for the get method from an expression of the form
- /// x => x.SomeProperty
- ///
- /// The type where the method is defined.
- /// The type for the property.
- /// Expression describing the property for which the get method is to be extracted.
- /// Corresponding .
- public static MethodInfo GetPropertyGetMethodInfo(Expression> expression)
- {
- var property = GetPropertyInfo(expression);
-
- var getMethod = property.GetGetMethod(true);
- if (getMethod == null)
- {
- throw new InvalidOperationException("Invalid expression form passed");
- }
-
- return getMethod;
- }
-
- ///
- /// Pull out a object for the set method from an expression of the form
- /// x => x.SomeProperty
- ///
- /// The type where the method is defined.
- /// The type for the property.
- /// Expression describing the property for which the set method is to be extracted.
- /// Corresponding .
- public static MethodInfo GetPropertySetMethodInfo(Expression> expression)
- {
- var property = GetPropertyInfo(expression);
-
- var setMethod = property.GetSetMethod(true);
- if (setMethod == null)
- {
- throw new InvalidOperationException("Invalid expression form passed");
- }
-
- return setMethod;
- }
-
- private static PropertyInfo GetPropertyInfo(LambdaExpression lambda)
- {
- var body = lambda.Body as MemberExpression;
- if (body == null)
- {
- throw new InvalidOperationException("Invalid expression form passed");
- }
-
- var property = body.Member as PropertyInfo;
- if (property == null)
- {
- throw new InvalidOperationException("Invalid expression form passed");
- }
-
- return property;
- }
-
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public static MemberInfo GetMemberInfo(Expression> expression)
- {
- Guard.ArgumentNotNull(expression, "expression");
-
- var body = expression.Body as MemberExpression;
- if (body == null)
- {
- throw new InvalidOperationException("invalid expression form passed");
- }
- var member = body.Member as MemberInfo;
- if (member == null)
- {
- throw new InvalidOperationException("Invalid expression form passed");
- }
-
- return member;
- }
-
- ///
- /// Pull out a object from an expression of the form () => new SomeType()
- ///
- /// The type where the constructor is defined.
- /// Expression invoking the desired constructor.
- /// Corresponding .
- public static ConstructorInfo GetConstructorInfo(Expression> expression)
- {
- Guard.ArgumentNotNull(expression, "expression");
-
- var body = expression.Body as NewExpression;
- if (body == null)
- {
- throw new InvalidOperationException("Invalid expression form passed");
- }
-
- return body.Constructor;
- }
-
- private static void GuardProperExpressionForm(Expression expression)
- {
- if (expression.NodeType != ExpressionType.Call)
- {
- throw new InvalidOperationException("Invalid expression form passed");
- }
- }
- }
-}
diff --git a/tests/AddInterfaceFixture.cs b/tests/AddInterfaceFixture.cs
deleted file mode 100644
index 7472f99..0000000
--- a/tests/AddInterfaceFixture.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Microsoft.Practices.Unity.InterceptionExtension.Tests.ObjectsUnderTest;
-using Microsoft.Practices.Unity.TestSupport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Unity.Interception;
-using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception;
-using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception;
-
-namespace Microsoft.Practices.Unity.InterceptionExtension.Tests
-{
- ///
- /// Summary description for AddInterfaceFixture
- ///
- [TestClass]
- public class AddInterfaceFixture
- {
- [TestMethod]
- public void CanProxyWithBehaviorThatAddsInterface()
- {
- var target = new MockDal();
- var proxied = Intercept.ThroughProxy(target,
- new InterfaceInterceptor(),
- new[] { new AdditionalInterfaceBehavior() });
-
- Assert.IsNotNull(proxied);
- }
-
- [TestMethod]
- public void BehaviorAddsInterface()
- {
- var target = new MockDal();
- var proxied = Intercept.ThroughProxy(target,
- new InterfaceInterceptor(),
- new[] { new AdditionalInterfaceBehavior() });
-
- Assert.IsNotNull(proxied as IAdditionalInterface);
- }
-
- [TestMethod]
- public void CanInvokeMethodAddedByBehavior()
- {
- var proxied = Intercept.NewInstance(
- new VirtualMethodInterceptor(),
- new[] { new AdditionalInterfaceBehavior() });
-
- Assert.AreEqual(10, ((IAdditionalInterface)proxied).DoNothing());
- }
-
- [TestMethod]
- public void CanManuallyAddAdditionalInterface()
- {
- var target = new MockDal();
- var proxied = Intercept.ThroughProxyWithAdditionalInterfaces(target,
- new InterfaceInterceptor(),
- new[] { new AdditionalInterfaceBehavior(false) },
- new[] { typeof(IAdditionalInterface) });
-
- Assert.IsNotNull(proxied as IAdditionalInterface);
- }
-
- [TestMethod]
- public void CanInvokeMethodOnManuallyAddedInterface()
- {
- var target = new MockDal();
- var proxied = Intercept.ThroughProxyWithAdditionalInterfaces(target,
- new InterfaceInterceptor(),
- new[] { new AdditionalInterfaceBehavior(false) },
- new[] { typeof(IAdditionalInterface) });
-
- Assert.AreEqual(10, ((IAdditionalInterface)proxied).DoNothing());
- }
- }
-}
diff --git a/tests/InterfaceInterception/ContainerInterfaceInterceptionFixture.cs b/tests/InterfaceInterception/ContainerInterfaceInterceptionFixture.cs
deleted file mode 100644
index 6c28075..0000000
--- a/tests/InterfaceInterception/ContainerInterfaceInterceptionFixture.cs
+++ /dev/null
@@ -1,161 +0,0 @@
-using Microsoft.Practices.Unity.InterceptionExtension.Tests.ObjectsUnderTest;
-using Microsoft.Practices.Unity.TestSupport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Unity;
-using Unity.Interception;
-using Unity.Interception.ContainerIntegration;
-using Unity.Interception.InterceptionBehaviors;
-using Unity.Interception.Interceptors;
-using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception;
-using Unity.Interception.PolicyInjection.MatchingRules;
-using Unity.Interception.PolicyInjection.Pipeline;
-using Unity.Interception.PolicyInjection.Policies;
-using Unity.Lifetime;
-
-namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.InterfaceInterception
-{
- [TestClass]
- public class ContainerInterfaceInterceptionFixture
- {
- [TestMethod]
- public void CanInterceptInstancesViaTheContainer()
- {
- IUnityContainer container = new UnityContainer()
- .AddNewExtension()
- .RegisterType()
- .Configure()
- .SetInterceptorFor(new InterfaceInterceptor())
- .AddPolicy("AlwaysMatches")
- .AddMatchingRule()
- .AddCallHandler("callCount", new ContainerControlledLifetimeManager())
- .Interception
- .Container;
-
- IDal dal = container.Resolve();
-
- Assert.IsTrue(dal is IInterceptingProxy);
-
- dal.Deposit(50.0);
- dal.Deposit(65.0);
- dal.Withdraw(15.0);
-
- CallCountHandler handler = (CallCountHandler)(container.Resolve("callCount"));
- Assert.AreEqual(3, handler.CallCount);
- }
-
- [TestMethod]
- public void CanInterceptOpenGenericInterfaces()
- {
- IUnityContainer container = new UnityContainer()
- .AddNewExtension()
- .RegisterType(typeof(InterfaceInterceptorFixture.IGenericOne<>), typeof(InterfaceInterceptorFixture.GenericImplementationOne<>))
- .Configure()
- .SetInterceptorFor(typeof(InterfaceInterceptorFixture.IGenericOne<>), new InterfaceInterceptor())
- .AddPolicy("AlwaysMatches")
- .AddMatchingRule()
- .AddCallHandler("callCount", new ContainerControlledLifetimeManager())
- .Interception
- .Container;
-
- InterfaceInterceptorFixture.IGenericOne target = container.Resolve>();
-
- decimal result = target.DoSomething(52m);
- Assert.AreEqual(52m, result);
- target.DoSomething(17m);
- target.DoSomething(84.2m);
-
- CallCountHandler handler = (CallCountHandler)(container.Resolve("callCount"));
- Assert.AreEqual(3, handler.CallCount);
- }
-
- [TestMethod]
- public void CanInterceptGenericInterfaceWithConstraints()
- {
- var container = new UnityContainer()
- .AddNewExtension()
- .RegisterType(typeof(IGenericInterfaceWithConstraints<>), typeof(ImplementsGenericInterface<>),
- new Interceptor(),
- new InterceptionBehavior(new NoopBehavior()));
-
- var result = container.Resolve>();
-
- Assert.IsNotNull(result as IInterceptingProxy);
- }
-
- public interface IGenericInterfaceWithConstraints
- where T : class
- {
- void TestMethod1();
-
- void TestMethod2()
- where T2 : struct;
-
- void TestMethod3()
- where T3 : class;
-
- void TestMethod4()
- where T4 : class, new();
-
- void TestMethod5()
- where T5 : InjectionPolicy;
-
- void TestMethod6()
- where T6 : IMatchingRule;
- }
-
- public class ImplementsGenericInterface : IGenericInterfaceWithConstraints
- where T : class
- {
- public void TestMethod1()
- {
- throw new NotImplementedException();
- }
-
- public void TestMethod2() where T2 : struct
- {
- throw new NotImplementedException();
- }
-
- public void TestMethod3() where T3 : class
- {
- throw new NotImplementedException();
- }
-
- public void TestMethod4() where T4 : class, new()
- {
- throw new NotImplementedException();
- }
-
- public void TestMethod5() where T5 : InjectionPolicy
- {
- throw new NotImplementedException();
- }
-
- public void TestMethod6() where T6 : IMatchingRule
- {
- throw new NotImplementedException();
- }
- }
-
- private class NoopBehavior : IInterceptionBehavior
- {
- public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
- {
- return getNext()(input, getNext);
- }
-
- public IEnumerable GetRequiredInterfaces()
- {
- return Enumerable.Empty();
- }
-
- public bool WillExecute
- {
- get { return true; }
- }
- }
- }
-}
diff --git a/tests/Specification/Diagnostic/Specification.Interception.Diagnostic.csproj b/tests/Specification/Diagnostic/Specification.Interception.Diagnostic.csproj
new file mode 100644
index 0000000..4c452c4
--- /dev/null
+++ b/tests/Specification/Diagnostic/Specification.Interception.Diagnostic.csproj
@@ -0,0 +1,21 @@
+
+
+
+ net48
+ false
+ true
+ ..\..\..\src\package.snk
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/Specification/Optimized/Specification.Interception.csproj b/tests/Specification/Optimized/Specification.Interception.csproj
new file mode 100644
index 0000000..38d445c
--- /dev/null
+++ b/tests/Specification/Optimized/Specification.Interception.csproj
@@ -0,0 +1,21 @@
+
+
+
+ net48
+ false
+ true
+ ..\..\..\src\package.snk
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/TestSupport/IAdditionalInterface.cs b/tests/TestSupport/IAdditionalInterface.cs
deleted file mode 100644
index 9d01fc4..0000000
--- a/tests/TestSupport/IAdditionalInterface.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Microsoft.Practices.Unity.TestSupport
-{
- public interface IAdditionalInterface
- {
- int DoNothing();
- }
-}
diff --git a/tests/Unit/Abstractions/TestFixtureBase.cs b/tests/Unit/Abstractions/TestFixtureBase.cs
new file mode 100644
index 0000000..2b4553f
--- /dev/null
+++ b/tests/Unit/Abstractions/TestFixtureBase.cs
@@ -0,0 +1,35 @@
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Unity.Interception.Tests
+{
+ public abstract class TestFixtureBase
+ {
+ #region Constants
+
+ public const string Name = "name";
+ public const string Legacy = "legacy";
+
+ #endregion
+
+
+ #region Container
+
+ protected IUnityContainer Container;
+
+ public virtual IUnityContainer GetContainer() => new UnityContainer().AddNewExtension()
+;
+
+ #endregion
+
+
+ #region Setup
+
+ [TestInitialize]
+ public virtual void Setup()
+ {
+ Container = GetContainer();
+ }
+
+ #endregion
+ }
+}
diff --git a/tests/TestSupport/AdditionalInterfaceBehavior.cs b/tests/Unit/Abstractions/TestObjects/AdditionalInterfaceBehavior.cs
similarity index 85%
rename from tests/TestSupport/AdditionalInterfaceBehavior.cs
rename to tests/Unit/Abstractions/TestObjects/AdditionalInterfaceBehavior.cs
index 1114188..59df386 100644
--- a/tests/TestSupport/AdditionalInterfaceBehavior.cs
+++ b/tests/Unit/Abstractions/TestObjects/AdditionalInterfaceBehavior.cs
@@ -1,27 +1,24 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using System.Reflection;
-using Microsoft.Practices.Unity.InterceptionExtension;
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.PolicyInjection.Pipeline;
-namespace Microsoft.Practices.Unity.TestSupport
+namespace Unity.Interception.Tests
{
public class AdditionalInterfaceBehavior : IInterceptionBehavior
{
- private static readonly MethodInfo DoNothingMethod = typeof(IAdditionalInterface).GetMethod("DoNothing");
- private bool implicitlyAddInterface = true;
+ private static readonly MethodInfo DoNothingMethod = typeof(IAdditionalInterface).GetMethod(nameof(IAdditionalInterface.DoNothing));
+ private readonly bool _isImplicit = true;
public AdditionalInterfaceBehavior()
{
- implicitlyAddInterface = true;
+ _isImplicit = true;
}
public AdditionalInterfaceBehavior(bool implicitlyAddInterface)
{
- this.implicitlyAddInterface = implicitlyAddInterface;
+ _isImplicit = implicitlyAddInterface;
}
///
@@ -51,7 +48,7 @@ private IMethodReturn ExecuteDoNothing(IMethodInvocation input)
/// The required interfaces.
public IEnumerable GetRequiredInterfaces()
{
- if (implicitlyAddInterface)
+ if (_isImplicit)
{
return new[] { typeof(IAdditionalInterface) };
}
diff --git a/tests/TestSupport/AlwaysMatchingRule.cs b/tests/Unit/Abstractions/TestObjects/AlwaysMatchingRule.cs
similarity index 88%
rename from tests/TestSupport/AlwaysMatchingRule.cs
rename to tests/Unit/Abstractions/TestObjects/AlwaysMatchingRule.cs
index f5c8e6a..832bb69 100644
--- a/tests/TestSupport/AlwaysMatchingRule.cs
+++ b/tests/Unit/Abstractions/TestObjects/AlwaysMatchingRule.cs
@@ -1,8 +1,7 @@
using System.Reflection;
-using Unity;
using Unity.Interception.PolicyInjection.MatchingRules;
-namespace Microsoft.Practices.Unity.TestSupport
+namespace Unity.Interception.Tests
{
///
/// A simple matching rule class that always matches. Useful when you want
diff --git a/tests/TestSupport/CallCountHandler.cs b/tests/Unit/Abstractions/TestObjects/CallCountHandler.cs
similarity index 87%
rename from tests/TestSupport/CallCountHandler.cs
rename to tests/Unit/Abstractions/TestObjects/CallCountHandler.cs
index 1b095e7..868445d 100644
--- a/tests/TestSupport/CallCountHandler.cs
+++ b/tests/Unit/Abstractions/TestObjects/CallCountHandler.cs
@@ -1,7 +1,6 @@
-using Unity;
-using Unity.Interception.PolicyInjection.Pipeline;
+using Unity.Interception.PolicyInjection.Pipeline;
-namespace Microsoft.Practices.Unity.TestSupport
+namespace Unity.Interception.Tests
{
public class CallCountHandler : ICallHandler
{
diff --git a/tests/TestSupport/CallCountInterceptionBehavior.cs b/tests/Unit/Abstractions/TestObjects/CallCountInterceptionBehavior.cs
similarity index 83%
rename from tests/TestSupport/CallCountInterceptionBehavior.cs
rename to tests/Unit/Abstractions/TestObjects/CallCountInterceptionBehavior.cs
index 811002a..9c74118 100644
--- a/tests/TestSupport/CallCountInterceptionBehavior.cs
+++ b/tests/Unit/Abstractions/TestObjects/CallCountInterceptionBehavior.cs
@@ -1,14 +1,13 @@
using System;
using System.Collections.Generic;
-using Unity;
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.PolicyInjection.Pipeline;
-namespace Microsoft.Practices.Unity.TestSupport
+namespace Unity.Interception.Tests
{
public class CallCountInterceptionBehavior : IInterceptionBehavior
{
- private int callCount;
+ private int _callCount;
[InjectionConstructor]
public CallCountInterceptionBehavior()
@@ -17,13 +16,13 @@ public CallCountInterceptionBehavior()
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
- ++callCount;
+ ++_callCount;
return getNext()(input, getNext);
}
public int CallCount
{
- get { return callCount; }
+ get { return _callCount; }
}
public IEnumerable GetRequiredInterfaces()
diff --git a/tests/TestSupport/DelegateInterceptionBehavior.cs b/tests/Unit/Abstractions/TestObjects/DelegateInterceptionBehavior.cs
similarity index 77%
rename from tests/TestSupport/DelegateInterceptionBehavior.cs
rename to tests/Unit/Abstractions/TestObjects/DelegateInterceptionBehavior.cs
index 0fd98e5..aa93882 100644
--- a/tests/TestSupport/DelegateInterceptionBehavior.cs
+++ b/tests/Unit/Abstractions/TestObjects/DelegateInterceptionBehavior.cs
@@ -1,19 +1,16 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
-using Microsoft.Practices.Unity.InterceptionExtension;
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.PolicyInjection.Pipeline;
-namespace Microsoft.Practices.Unity.TestSupport
+namespace Unity.Interception.Tests
{
public class DelegateInterceptionBehavior : IInterceptionBehavior
{
public static readonly Func> NoRequiredInterfaces = () => Type.EmptyTypes;
- private readonly Func invoke;
- private readonly Func> requiredInterfaces;
+ private readonly Func _invoke;
+ private readonly Func> _requiredInterfaces;
public DelegateInterceptionBehavior(Func invoke)
: this(invoke, NoRequiredInterfaces)
@@ -23,18 +20,18 @@ public DelegateInterceptionBehavior(
Func invoke,
Func> requiredInterfaces)
{
- this.invoke = invoke;
- this.requiredInterfaces = requiredInterfaces;
+ _invoke = invoke;
+ _requiredInterfaces = requiredInterfaces;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
- return this.invoke(input, getNext);
+ return _invoke(input, getNext);
}
public IEnumerable GetRequiredInterfaces()
{
- return this.requiredInterfaces();
+ return _requiredInterfaces();
}
///
diff --git a/tests/TestSupport/GlobalCountCallHandler.cs b/tests/Unit/Abstractions/TestObjects/GlobalCountCallHandler.cs
similarity index 57%
rename from tests/TestSupport/GlobalCountCallHandler.cs
rename to tests/Unit/Abstractions/TestObjects/GlobalCountCallHandler.cs
index fc79797..3e5c1c5 100644
--- a/tests/TestSupport/GlobalCountCallHandler.cs
+++ b/tests/Unit/Abstractions/TestObjects/GlobalCountCallHandler.cs
@@ -1,15 +1,13 @@
using System.Collections.Generic;
-using Unity;
using Unity.Interception.PolicyInjection.Pipeline;
using Unity.Interception.PolicyInjection.Policies;
-namespace Microsoft.Practices.Unity.TestSupport
+namespace Unity.Interception.Tests
{
public class GlobalCountCallHandler : ICallHandler
{
public static Dictionary Calls = new Dictionary();
- private string callHandlerName;
- private int order = 0;
+ private string _callHandlerName;
[InjectionConstructor]
public GlobalCountCallHandler()
@@ -19,7 +17,7 @@ public GlobalCountCallHandler()
public GlobalCountCallHandler(string callHandlerName)
{
- this.callHandlerName = callHandlerName;
+ this._callHandlerName = callHandlerName;
}
#region ICallHandler Members
@@ -27,25 +25,15 @@ public GlobalCountCallHandler(string callHandlerName)
///
/// Gets or sets the order in which the handler will be executed
///
- public int Order
- {
- get
- {
- return order;
- }
- set
- {
- order = value;
- }
- }
+ public int Order { get; set; } = 0;
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
- if (!Calls.ContainsKey(callHandlerName))
+ if (!Calls.ContainsKey(_callHandlerName))
{
- Calls.Add(callHandlerName, 0);
+ Calls.Add(_callHandlerName, 0);
}
- Calls[callHandlerName]++;
+ Calls[_callHandlerName]++;
return getNext().Invoke(input, getNext);
}
@@ -55,17 +43,11 @@ public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getN
public class GlobalCountCallHandlerAttribute : HandlerAttribute
{
- public override ICallHandler CreateHandler(IUnityContainer ignored)
+ public override ICallHandler CreateHandler(IUnityContainer _)
{
- return new GlobalCountCallHandler(this.handlerName);
+ return new GlobalCountCallHandler(HandlerName);
}
- private string handlerName;
-
- public string HandlerName
- {
- get { return this.handlerName; }
- set { this.handlerName = value; }
- }
+ public string HandlerName { get; set; }
}
}
diff --git a/tests/Unit/Abstractions/TestObjects/IAdditionalInterface.cs b/tests/Unit/Abstractions/TestObjects/IAdditionalInterface.cs
new file mode 100644
index 0000000..b908a21
--- /dev/null
+++ b/tests/Unit/Abstractions/TestObjects/IAdditionalInterface.cs
@@ -0,0 +1,7 @@
+namespace Unity.Interception.Tests
+{
+ public interface IAdditionalInterface
+ {
+ int DoNothing();
+ }
+}
diff --git a/tests/ObjectsUnderTest/MockDal.cs b/tests/Unit/Abstractions/TestObjects/MockDal.cs
similarity index 87%
rename from tests/ObjectsUnderTest/MockDal.cs
rename to tests/Unit/Abstractions/TestObjects/MockDal.cs
index 76b325c..a2a606a 100644
--- a/tests/ObjectsUnderTest/MockDal.cs
+++ b/tests/Unit/Abstractions/TestObjects/MockDal.cs
@@ -1,11 +1,7 @@
-
-
-using System;
-using System.Collections.Specialized;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System;
using Unity.Interception.PolicyInjection.Policies;
-namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.ObjectsUnderTest
+namespace Unity.Interception.Tests
{
public interface IDal
{
@@ -35,6 +31,7 @@ public double Balance
set { balance = value; }
}
+#pragma warning disable IDE0060 // Remove unused parameter
public int DoSomething(string x)
{
if (throwException)
@@ -43,6 +40,7 @@ public int DoSomething(string x)
}
return 42;
}
+#pragma warning restore IDE0060 // Remove unused parameter
#region IDal Members
diff --git a/tests/TestSupport/NaiveINotifyPropertyChangedInterceptionBehavior.cs b/tests/Unit/Abstractions/TestObjects/NaiveINotifyPropertyChangedInterceptionBehavior.cs
similarity index 81%
rename from tests/TestSupport/NaiveINotifyPropertyChangedInterceptionBehavior.cs
rename to tests/Unit/Abstractions/TestObjects/NaiveINotifyPropertyChangedInterceptionBehavior.cs
index 342fa7b..f781e9b 100644
--- a/tests/TestSupport/NaiveINotifyPropertyChangedInterceptionBehavior.cs
+++ b/tests/Unit/Abstractions/TestObjects/NaiveINotifyPropertyChangedInterceptionBehavior.cs
@@ -1,19 +1,16 @@
-
-
-using System;
+using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
-using Microsoft.Practices.Unity.InterceptionExtension;
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.PolicyInjection.Pipeline;
-namespace Microsoft.Practices.Unity.TestSupport
+namespace Unity.Interception.Tests
{
public class NaiveINotifyPropertyChangedInterceptionBehavior : IInterceptionBehavior
{
- private readonly object handlerLock = new object();
- private PropertyChangedEventHandler handler;
+ private readonly object _handlerLock = new object();
+ private PropertyChangedEventHandler _handler;
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
@@ -32,7 +29,7 @@ public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehavior
if (property != null)
{
- var currentHandler = this.handler;
+ var currentHandler = _handler;
if (currentHandler != null)
{
try
@@ -57,16 +54,16 @@ private IMethodReturn InvokeINotifyPropertyChangedMethod(IMethodInvocation input
switch (input.MethodBase.Name)
{
case "add_PropertyChanged":
- lock (handlerLock)
+ lock (_handlerLock)
{
- handler = (PropertyChangedEventHandler)Delegate.Combine(handler, (Delegate)input.Arguments[0]);
+ _handler = (PropertyChangedEventHandler)Delegate.Combine(_handler, (Delegate)input.Arguments[0]);
}
break;
case "remove_PropertyChanged":
- lock (handlerLock)
+ lock (_handlerLock)
{
- handler = (PropertyChangedEventHandler)Delegate.Remove(handler, (Delegate)input.Arguments[0]);
+ _handler = (PropertyChangedEventHandler)Delegate.Remove(_handler, (Delegate)input.Arguments[0]);
}
break;
diff --git a/tests/TestSupport/WrappableObjects.Desktop.cs b/tests/Unit/Abstractions/TestObjects/WrappableObjects.Desktop.cs
similarity index 52%
rename from tests/TestSupport/WrappableObjects.Desktop.cs
rename to tests/Unit/Abstractions/TestObjects/WrappableObjects.Desktop.cs
index 11e6f2c..f29f08d 100644
--- a/tests/TestSupport/WrappableObjects.Desktop.cs
+++ b/tests/Unit/Abstractions/TestObjects/WrappableObjects.Desktop.cs
@@ -1,11 +1,6 @@
-
+using System;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace Microsoft.Practices.Unity.TestSupport
+namespace Unity.Interception.Tests
{
public partial class Wrappable : MarshalByRefObject
{
diff --git a/tests/TestSupport/WrappableObjects.cs b/tests/Unit/Abstractions/TestObjects/WrappableObjects.cs
similarity index 96%
rename from tests/TestSupport/WrappableObjects.cs
rename to tests/Unit/Abstractions/TestObjects/WrappableObjects.cs
index 58a154f..8660eed 100644
--- a/tests/TestSupport/WrappableObjects.cs
+++ b/tests/Unit/Abstractions/TestObjects/WrappableObjects.cs
@@ -1,8 +1,4 @@
-
-
-using System;
-
-namespace Microsoft.Practices.Unity.TestSupport
+namespace Unity.Interception.Tests
{
public class WrappableThroughInterface : Interface, InterfaceA
{
diff --git a/tests/InterceptionFixture.Desktop.cs b/tests/Unit/Extension/InterceptionFixture.Desktop.cs
similarity index 99%
rename from tests/InterceptionFixture.Desktop.cs
rename to tests/Unit/Extension/InterceptionFixture.Desktop.cs
index ae1b34c..9151fc0 100644
--- a/tests/InterceptionFixture.Desktop.cs
+++ b/tests/Unit/Extension/InterceptionFixture.Desktop.cs
@@ -1,5 +1,4 @@
-using Microsoft.Practices.Unity.TestSupport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Runtime.Remoting;
using Unity;
@@ -11,9 +10,10 @@
using Unity.Interception.PolicyInjection.MatchingRules;
using Unity.Interception.PolicyInjection.Pipeline;
using Unity.Interception.PolicyInjection.Policies;
+using Unity.Interception.Tests;
using Unity.Lifetime;
-namespace Microsoft.Practices.Unity.InterceptionExtension.Tests
+namespace Extension.Tests
{
public partial class InterceptionFixture
{
diff --git a/tests/InterceptionFixture.cs b/tests/Unit/Extension/InterceptionFixture.cs
similarity index 90%
rename from tests/InterceptionFixture.cs
rename to tests/Unit/Extension/InterceptionFixture.cs
index be1cbde..0893612 100644
--- a/tests/InterceptionFixture.cs
+++ b/tests/Unit/Extension/InterceptionFixture.cs
@@ -1,5 +1,4 @@
-using Microsoft.Practices.Unity.TestSupport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
using Unity;
using Unity.Interception;
using Unity.Interception.ContainerIntegration;
@@ -8,25 +7,24 @@
using Unity.Interception.PolicyInjection;
using Unity.Interception.PolicyInjection.MatchingRules;
using Unity.Interception.PolicyInjection.Pipeline;
+using Unity.Interception.Tests;
using Unity.Lifetime;
-namespace Microsoft.Practices.Unity.InterceptionExtension.Tests
+namespace Extension.Tests
{
[TestClass]
- public partial class InterceptionFixture
+ public partial class InterceptionFixture : TestFixtureBase
{
[TestMethod]
public void AttributeDrivenPolicyIsAddedByDefault()
{
GlobalCountCallHandler.Calls.Clear();
- IUnityContainer container = new UnityContainer();
- container.AddNewExtension();
- container.RegisterType(
+ Container.RegisterType(
new Interceptor(),
new InterceptionBehavior());
- Interface wrappedOverInterface = container.Resolve();
+ Interface wrappedOverInterface = Container.Resolve();
wrappedOverInterface.Method();
Assert.AreEqual(1, GlobalCountCallHandler.Calls["WrappableThroughInterfaceWithAttributes-Method"]);
@@ -189,23 +187,15 @@ public void CanInterceptExistingWrappedObjectOverInterface()
private IUnityContainer CreateContainer(string globalCallHandlerName)
{
- IUnityContainer container = new UnityContainer();
-
- container.AddNewExtension();
-
- container.RegisterInstance(
- "alwaystrue",
- new AlwaysMatchingRule());
- container.RegisterInstance(
- "globalCountHandler",
- new GlobalCountCallHandler(globalCallHandlerName));
+ Container.RegisterInstance("alwaystrue", new AlwaysMatchingRule());
+ Container.RegisterInstance("globalCountHandler", new GlobalCountCallHandler(globalCallHandlerName));
- container.Configure()
+ Container.Configure()
.AddPolicy("policy")
.AddMatchingRule("alwaystrue")
.AddCallHandler("globalCountHandler");
- return container;
+ return Container;
}
[TestMethod]
diff --git a/tests/Unit/Extension/Interface/InterfaceInterception.cs b/tests/Unit/Extension/Interface/InterfaceInterception.cs
new file mode 100644
index 0000000..d991dea
--- /dev/null
+++ b/tests/Unit/Extension/Interface/InterfaceInterception.cs
@@ -0,0 +1,159 @@
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Unit.Tests;
+using Unity;
+using Unity.Interception;
+using Unity.Interception.ContainerIntegration;
+using Unity.Interception.InterceptionBehaviors;
+using Unity.Interception.Interceptors;
+using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception;
+using Unity.Interception.PolicyInjection.MatchingRules;
+using Unity.Interception.PolicyInjection.Pipeline;
+using Unity.Interception.PolicyInjection.Policies;
+using Unity.Interception.Tests;
+using Unity.Lifetime;
+
+namespace Extension.Tests
+{
+ [TestClass]
+ public class InterfaceInterception : TestFixtureBase
+ {
+ [TestMethod]
+ public void CanInterceptInstancesViaTheContainer()
+ {
+ Container
+ .RegisterType()
+ .Configure()
+ .SetInterceptorFor(new InterfaceInterceptor())
+ .AddPolicy("AlwaysMatches")
+ .AddMatchingRule()
+ .AddCallHandler("callCount", new ContainerControlledLifetimeManager());
+
+ IDal dal = Container.Resolve();
+
+ Assert.IsTrue(dal is IInterceptingProxy);
+
+ dal.Deposit(50.0);
+ dal.Deposit(65.0);
+ dal.Withdraw(15.0);
+
+ CallCountHandler handler = (CallCountHandler)(Container.Resolve("callCount"));
+ Assert.AreEqual(3, handler.CallCount);
+ }
+
+ [TestMethod]
+ public void CanInterceptOpenGenericInterfaces()
+ {
+ Container
+ .RegisterType(typeof(InterfaceInterceptorFixture.IGenericOne<>), typeof(InterfaceInterceptorFixture.GenericImplementationOne<>))
+ .Configure()
+ .SetInterceptorFor(typeof(InterfaceInterceptorFixture.IGenericOne<>), new InterfaceInterceptor())
+ .AddPolicy("AlwaysMatches")
+ .AddMatchingRule()
+ .AddCallHandler("callCount", new ContainerControlledLifetimeManager());
+
+ InterfaceInterceptorFixture.IGenericOne target = Container.Resolve>();
+
+ decimal result = target.DoSomething(52m);
+ Assert.AreEqual(52m, result);
+ target.DoSomething(17m);
+ target.DoSomething(84.2m);
+
+ CallCountHandler handler = (CallCountHandler)(Container.Resolve("callCount"));
+ Assert.AreEqual(3, handler.CallCount);
+ }
+
+ [TestMethod]
+ public void CanInterceptGenericInterfaceWithConstraints()
+ {
+ Container
+ .RegisterType(typeof(IGenericInterfaceWithConstraints<>), typeof(ImplementsGenericInterface<>),
+ new Interceptor(),
+ new InterceptionBehavior(new NoopBehavior()));
+
+ var result = Container.Resolve>();
+
+ Assert.IsNotNull(result as IInterceptingProxy);
+ }
+ }
+
+
+ #region Test Data
+
+ public interface IGenericInterfaceWithConstraints
+ where T : class
+ {
+ void TestMethod1();
+
+ void TestMethod2()
+ where T2 : struct;
+
+ void TestMethod3()
+ where T3 : class;
+
+ void TestMethod4()
+ where T4 : class, new();
+
+ void TestMethod5()
+ where T5 : InjectionPolicy;
+
+ void TestMethod6()
+ where T6 : IMatchingRule;
+ }
+
+ public class ImplementsGenericInterface : IGenericInterfaceWithConstraints
+ where T : class
+ {
+ public void TestMethod1()
+ {
+ throw new NotImplementedException();
+ }
+
+ public void TestMethod2() where T2 : struct
+ {
+ throw new NotImplementedException();
+ }
+
+ public void TestMethod3() where T3 : class
+ {
+ throw new NotImplementedException();
+ }
+
+ public void TestMethod4() where T4 : class, new()
+ {
+ throw new NotImplementedException();
+ }
+
+ public void TestMethod5() where T5 : InjectionPolicy
+ {
+ throw new NotImplementedException();
+ }
+
+ public void TestMethod6() where T6 : IMatchingRule
+ {
+ throw new NotImplementedException();
+ }
+ }
+
+ public class NoopBehavior : IInterceptionBehavior
+ {
+ public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
+ {
+ return getNext()(input, getNext);
+ }
+
+ public IEnumerable GetRequiredInterfaces()
+ {
+ return Enumerable.Empty();
+ }
+
+ public bool WillExecute
+ {
+ get { return true; }
+ }
+ }
+
+ #endregion
+}
diff --git a/tests/VirtualMethodInterception/ContainerVirtualMethodInterceptionFixture.cs b/tests/Unit/Extension/Method/VirtualMethodInterception.cs
similarity index 75%
rename from tests/VirtualMethodInterception/ContainerVirtualMethodInterceptionFixture.cs
rename to tests/Unit/Extension/Method/VirtualMethodInterception.cs
index 33c0664..795a6e8 100644
--- a/tests/VirtualMethodInterception/ContainerVirtualMethodInterceptionFixture.cs
+++ b/tests/Unit/Extension/Method/VirtualMethodInterception.cs
@@ -1,5 +1,4 @@
-using Microsoft.Practices.Unity.TestSupport;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.ComponentModel;
using Unity;
@@ -12,16 +11,13 @@
using Unity.Interception.PolicyInjection.MatchingRules;
using Unity.Interception.PolicyInjection.Pipeline;
using Unity.Interception.PolicyInjection.Policies;
+using Unity.Interception.Tests;
using Unity.Lifetime;
-namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.VirtualMethodInterception
+namespace Extension.Tests
{
- ///
- /// Tests for the virtual method interception mechanism as invoked
- /// through the container.
- ///
[TestClass]
- public class ContainerVirtualMethodInterceptionFixture
+ public class VirtualMethodInterception : TestFixtureBase
{
[TestMethod]
public void InterceptedClassGetsReturned()
@@ -29,11 +25,14 @@ public void InterceptedClassGetsReturned()
CallCountHandler h1 = new CallCountHandler();
CallCountHandler h2 = new CallCountHandler();
- IUnityContainer container = GetConfiguredContainer(h1, h2);
- AddPoliciesToContainer(container);
- ConfigureInterceptionWithRegisterType(container);
+ Container
+ .RegisterInstance("h1", h1)
+ .RegisterInstance("h2", h2);
+
+ AddPoliciesToContainer(Container);
+ ConfigureInterceptionWithRegisterType(Container);
- Interceptee target = container.Resolve();
+ Interceptee target = Container.Resolve();
Assert.AreNotSame(typeof(Interceptee), target.GetType());
}
@@ -44,8 +43,7 @@ public void AttachedHandlersAreCalled()
CallCountHandler h1 = new CallCountHandler();
CallCountHandler h2 = new CallCountHandler();
- IUnityContainer container = new UnityContainer()
- .AddNewExtension()
+ Container
.RegisterInstance("h1", h1)
.RegisterInstance("h2", h2)
.RegisterType(
@@ -58,19 +56,16 @@ public void AttachedHandlersAreCalled()
.Interception
.AddPolicy("methodTwo")
.AddMatchingRule(new InjectionConstructor("MethodTwo"))
- .AddCallHandler("h2")
- .Interception.Container;
-
- Interceptee target = container.Resolve();
-
- int oneCount = 0;
- int twoCount = 0;
+ .AddCallHandler("h2");
+ Interceptee target = Container.Resolve();
+ int oneCount;
for (oneCount = 0; oneCount < 2; ++oneCount)
{
target.MethodOne();
}
+ int twoCount;
for (twoCount = 0; twoCount < 3; ++twoCount)
{
target.MethodTwo("hi", twoCount);
@@ -83,16 +78,13 @@ public void AttachedHandlersAreCalled()
[TestMethod]
public void RegisteringInterceptionOnOpenGenericsLetsYouResolveMultipleClosedClasses()
{
- IUnityContainer container = new UnityContainer()
- .AddNewExtension();
-
- AddPoliciesToContainer(container);
+ AddPoliciesToContainer(Container);
- container.Configure()
+ Container.Configure()
.SetDefaultInterceptorFor(typeof(GenericFactory<>), new VirtualMethodInterceptor());
- GenericFactory resultOne = container.Resolve>();
- GenericFactory resultTwo = container.Resolve>();
+ GenericFactory resultOne = Container.Resolve>();
+ GenericFactory resultTwo = Container.Resolve>();
Assert.IsTrue(resultOne is IInterceptingProxy);
Assert.IsTrue(resultTwo is IInterceptingProxy);
@@ -118,17 +110,14 @@ public virtual void TestNewVirtualOverride()
[TestMethod]
public void CanInterceptWithInterceptorSetAsDefaultForBaseClassWithMultipleImplementations()
{
- IUnityContainer container =
- new UnityContainer()
+ Container
.RegisterType("one")
.RegisterType("two")
- .AddNewExtension()
.Configure()
- .SetDefaultInterceptorFor(new VirtualMethodInterceptor())
- .Container;
+ .SetDefaultInterceptorFor(new VirtualMethodInterceptor());
- BaseClass instanceOne = container.Resolve("one");
- BaseClass instanceTwo = container.Resolve("two");
+ BaseClass instanceOne = Container.Resolve("one");
+ BaseClass instanceTwo = Container.Resolve("two");
Assert.AreEqual("ImplementationOne", instanceOne.Method());
Assert.AreEqual("ImplementationTwo", instanceTwo.Method());
@@ -137,14 +126,12 @@ public void CanInterceptWithInterceptorSetAsDefaultForBaseClassWithMultipleImple
[TestMethod]
public void CanAddInterceptionBehaviorsWithRequiredInterfaces()
{
- IUnityContainer container =
- new UnityContainer()
- .AddNewExtension()
+ Container
.RegisterType(
new Interceptor(),
new InterceptionBehavior(new NaiveINotifyPropertyChangedInterceptionBehavior()));
- ClassWithVirtualProperty instance = container.Resolve();
+ ClassWithVirtualProperty instance = Container.Resolve();
string changedProperty = null;
((INotifyPropertyChanged)instance).PropertyChanged += (s, a) => changedProperty = a.PropertyName;
@@ -157,31 +144,25 @@ public void CanAddInterceptionBehaviorsWithRequiredInterfaces()
[TestMethod]
public void ResolvingKeyForTheSecondTimeAfterAddingBehaviorWithRequiredInterfaceReflectsLastConfiguration()
{
- IUnityContainer container =
- new UnityContainer()
- .AddNewExtension()
- .RegisterType(new Interceptor());
+ Container.RegisterType(new Interceptor());
- Assert.IsFalse(container.Resolve() is INotifyPropertyChanged);
+ Assert.IsFalse(Container.Resolve() is INotifyPropertyChanged);
- container
+ Container
.RegisterType(new Interceptor(),
new InterceptionBehavior(
new NaiveINotifyPropertyChangedInterceptionBehavior()));
- Assert.IsTrue(container.Resolve() is INotifyPropertyChanged);
+ Assert.IsTrue(Container.Resolve() is INotifyPropertyChanged);
}
[TestMethod]
public void GeneratedDerivedTypeIsCached()
{
- IUnityContainer container =
- new UnityContainer()
- .AddNewExtension()
- .RegisterType(new Interceptor());
+ Container.RegisterType