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 Select(Type type, IPolicySet registration) - { - object originalConstructor = - OriginalConstructorSelectorPolicy.Select(type, registration) - .First(); - switch (originalConstructor) - { - case ConstructorInfo info: - return new []{ FromConstructorInfo(info, InterceptingType) }; - - case SelectedConstructor selectedConstructor: - return new []{ FromSelectedConstructor(selectedConstructor, InterceptingType) }; - - case MethodBase methodBaseMember: - return new []{ FromMethodBaseMember(methodBaseMember, InterceptingType) }; - } - - throw new InvalidOperationException("Unknown type"); - } - - - private static SelectedConstructor FromMethodBaseMember(MethodBase methodBaseMember, Type type) - { - var cInfo = methodBaseMember.MemberInfo(type); - var args = methodBaseMember.Data; - - var newConstructorInfo = type.GetConstructor(cInfo.GetParameters().Select(pi => pi.ParameterType).ToArray()); - - return new SelectedConstructor(newConstructorInfo, args); - } - - private static SelectedConstructor FromSelectedConstructor(SelectedConstructor selectedConstructor, Type interceptingType) - { - var originalParams = selectedConstructor.Constructor.GetParameters(); - - var newConstructorInfo = - interceptingType.GetConstructor(originalParams.Select(pi => pi.ParameterType).ToArray()); - - var newConstructor = new SelectedConstructor(newConstructorInfo, originalParams); - - return newConstructor; - } - - private static SelectedConstructor FromConstructorInfo(ConstructorInfo info, Type interceptingType) - { - var originalParams = info.GetParameters(); - - var newConstructorInfo = interceptingType.GetConstructor(originalParams.Select(pi => pi.ParameterType).ToArray()); - - return new SelectedConstructor(newConstructorInfo); - } - - public static void SetPolicyForInterceptingType(ref BuilderContext context, Type interceptingType) - { - var currentSelectorPolicy = - GetPolicy>(ref context); - - if (!(currentSelectorPolicy is DerivedTypeConstructorSelectorPolicy currentDerivedTypeSelectorPolicy)) - { - context.Registration.Set(typeof(ISelect), - new DerivedTypeConstructorSelectorPolicy(interceptingType, currentSelectorPolicy)); - } - else if (currentDerivedTypeSelectorPolicy.InterceptingType != interceptingType) - { - context.Registration.Set(typeof(ISelect), - new DerivedTypeConstructorSelectorPolicy(interceptingType, - currentDerivedTypeSelectorPolicy.OriginalConstructorSelectorPolicy)); - } - } - } - #endregion } } diff --git a/src/Unity.Interception.csproj b/src/Unity.Interception.csproj index 07a5d61..86987e6 100644 --- a/src/Unity.Interception.csproj +++ b/src/Unity.Interception.csproj @@ -1,10 +1,6 @@  - - - $(Version).0 - $(Version).0 Unity.Interception Unity Interception Copyright © Unity Container Project 2018 @@ -19,9 +15,38 @@ true package.snk false - netstandard2.0;net47;net46;net45;netcoreapp2.0 + latest + enable + netstandard2.0;net48;net47;net46;net45;netcoreapp2.0 - + + + true + Portable + + + + false + Full + + + + + + + ..\..\Container\src\Unity.Container.csproj + + + + + + + + + + + + True @@ -36,7 +61,7 @@ - + @@ -57,29 +82,6 @@ - - true - Portable - - - - false - Full - - - - - ..\..\Container\src\Unity.Container.csproj - - - - - - - - - - @@ -97,7 +99,10 @@ + + + true true @@ -105,7 +110,7 @@ - + all runtime; build; native; contentfiles; analyzers diff --git a/src/Utilities/EnumerableExtensions.cs b/src/Utilities/EnumerableExtensions.cs deleted file mode 100644 index 66c233c..0000000 --- a/src/Utilities/EnumerableExtensions.cs +++ /dev/null @@ -1,74 +0,0 @@ - - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Unity.Interception.Utilities -{ - /// - /// The almost inevitable collection of extra helper methods on - /// to augment the rich set of what - /// LINQ already gives us. - /// - public static class EnumerableExtensions - { - /// - /// Execute the provided on every item in . - /// - /// Type of the items stored in - /// Sequence of items to process. - /// Code to run over each item. - public static void ForEach(this IEnumerable sequence, Action action) - { - Guard.ArgumentNotNull(sequence, "sequence"); - - foreach (var item in sequence) - { - action(item); - } - } - - /// - /// Create a single string from a sequence of items, separated by the provided , - /// and with the conversion to string done by the given . - /// - /// This method does basically the same thing as , - /// but will work on any sequence of items, not just arrays. - /// Type of items in the sequence. - /// Sequence of items to convert. - /// Separator to place between the items in the string. - /// The conversion function to change TItem -> string. - /// The resulting string. - public static string JoinStrings(this IEnumerable sequence, string separator, Func converter) - { - var sb = new StringBuilder(); - sequence.Aggregate(sb, (builder, item) => - { - if (builder.Length > 0) - { - builder.Append(separator); - } - builder.Append(converter(item)); - return builder; - }); - return sb.ToString(); - } - - /// - /// Create a single string from a sequence of items, separated by the provided , - /// and with the conversion to string done by the item's method. - /// - /// This method does basically the same thing as , - /// but will work on any sequence of items, not just arrays. - /// Type of items in the sequence. - /// Sequence of items to convert. - /// Separator to place between the items in the string. - /// The resulting string. - public static string JoinStrings(this IEnumerable sequence, string separator) - { - return sequence.JoinStrings(separator, item => item.ToString()); - } - } -} diff --git a/src/Utilities/Guard.cs b/src/Utilities/Guard.cs index 4f2bdd3..472cc26 100644 --- a/src/Utilities/Guard.cs +++ b/src/Utilities/Guard.cs @@ -1,6 +1,4 @@ - - -using System; +using System; using System.Globalization; using System.Reflection; @@ -11,42 +9,6 @@ namespace Unity.Interception.Utilities /// 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(new Interceptor()); - ClassWithVirtualProperty instanceOne = container.Resolve(); - ClassWithVirtualProperty instanceTwo = container.Resolve(); + ClassWithVirtualProperty instanceOne = Container.Resolve(); + ClassWithVirtualProperty instanceTwo = Container.Resolve(); Assert.AreSame(typeof(ClassWithVirtualProperty), instanceOne.GetType().BaseType); Assert.AreSame(instanceOne.GetType(), instanceTwo.GetType()); @@ -192,15 +173,12 @@ public void CanInterceptClassWithSingleNonDefaultConstructor() { CallCountInterceptionBehavior callCountBehavior = new CallCountInterceptionBehavior(); - IUnityContainer container = - new UnityContainer() - .AddNewExtension() - .RegisterType( + Container.RegisterType( new InjectionConstructor("some value"), new Interceptor(), new InterceptionBehavior(callCountBehavior)); - ClassWithSingleNonDefaultConstructor instance = container.Resolve(); + var instance = Container.Resolve(); string value = instance.GetValue(); @@ -211,46 +189,18 @@ public void CanInterceptClassWithSingleNonDefaultConstructor() [TestMethod] public void CanInterceptGenericTypeWithGenericMethodsWithConstraints() { - var container = new UnityContainer() - .AddNewExtension() - .RegisterType(typeof(GenericTypeWithGenericMethodsAndConstraints<>), + Container.RegisterType(typeof(GenericTypeWithGenericMethodsAndConstraints<>), new Interceptor()); - var result = container.Resolve>(); + var result = Container.Resolve>(); Type interceptedType = result.GetType(); - Type genericInterceptedType = interceptedType.GetGenericTypeDefinition(); + _ = interceptedType.GetGenericTypeDefinition(); Assert.IsFalse(interceptedType.ContainsGenericParameters); Assert.IsTrue(interceptedType.IsGenericType); Assert.IsFalse(interceptedType.IsGenericTypeDefinition); } - protected virtual IUnityContainer GetContainer() - { - IUnityContainer container = new UnityContainer() - .AddNewExtension() - .RegisterType("AlwaysMatchingRule") - .RegisterType("TestCallHandler", new ContainerControlledLifetimeManager()); - - container.Configure() - .SetDefaultInterceptorFor(new VirtualMethodInterceptor()) - .AddPolicy("Rules") - .AddMatchingRule("AlwaysMatchingRule") - .AddCallHandler("TestCallHandler"); - - return container; - } - - private IUnityContainer GetConfiguredContainer(ICallHandler h1, ICallHandler h2) - { - IUnityContainer container = new UnityContainer() - .AddNewExtension() - .RegisterInstance("h1", h1) - .RegisterInstance("h2", h2); - - return container; - } - private IUnityContainer AddPoliciesToContainer(IUnityContainer container) { container.Configure() @@ -261,6 +211,7 @@ private IUnityContainer AddPoliciesToContainer(IUnityContainer container) .AddPolicy("MethodTwo") .AddMatchingRule(new InjectionConstructor("MethodTwo")) .AddCallHandler("h2"); + return container; } @@ -271,8 +222,27 @@ private IUnityContainer ConfigureInterceptionWithRegisterType(IUnityContainer co new InterceptionBehavior()); return container; } + + public override IUnityContainer GetContainer() + { + IUnityContainer container = base.GetContainer() + .RegisterType("AlwaysMatchingRule") + .RegisterType("TestCallHandler", new ContainerControlledLifetimeManager()); + + container.Configure() + .SetDefaultInterceptorFor(new VirtualMethodInterceptor()) + .AddPolicy("Rules") + .AddMatchingRule("AlwaysMatchingRule") + .AddCallHandler("TestCallHandler"); + + return container; + } + } + + #region Test Data + public class Interceptee { public virtual int MethodOne() @@ -383,7 +353,7 @@ public class ClassWithVirtualProperty public class ClassWithSingleNonDefaultConstructor { - private string value; + private readonly string value; public ClassWithSingleNonDefaultConstructor(string value) { @@ -434,4 +404,6 @@ public virtual void TestMethod6() where T6 : IMatchingRule { } } + + #endregion } diff --git a/tests/PolicyFixture.cs b/tests/Unit/Extension/Policy/PolicyFixture.cs similarity index 71% rename from tests/PolicyFixture.cs rename to tests/Unit/Extension/Policy/PolicyFixture.cs index 1083a6c..a22fa9e 100644 --- a/tests/PolicyFixture.cs +++ b/tests/Unit/Extension/Policy/PolicyFixture.cs @@ -1,10 +1,7 @@ - - -using System; +using System; using System.Collections; using System.Collections.Generic; using System.Reflection; -using Microsoft.Practices.Unity.InterceptionExtension.Tests.ObjectsUnderTest; using Microsoft.Practices.Unity.TestSupport; using Microsoft.VisualStudio.TestTools.UnitTesting; using Unity; @@ -12,54 +9,55 @@ using Unity.Interception.PolicyInjection.MatchingRules; using Unity.Interception.PolicyInjection.Pipeline; using Unity.Interception.PolicyInjection.Policies; +using Unity.Interception.Tests; -namespace Microsoft.Practices.Unity.InterceptionExtension.Tests +namespace Extension.Tests { /// /// Tests for the Policy class /// [TestClass] - public class PolicyFixture + public class PolicyFixture : TestFixtureBase { - //[TestMethod] - //public void ShouldInitializeToEmpty() - //{ - // RuleDrivenPolicy p = new RuleDrivenPolicy("Empty"); - // Assert.AreEqual("Empty", p.Name); - // Assert.AreEqual(0, p.RuleSet.Count); - // Assert.AreEqual(0, p.Handlers.Count); - //} - - //[TestMethod] - //public void ShouldPreserveHandlerOrder() - //{ - // RuleDrivenPolicy p = new RuleDrivenPolicy("OrderedHandlers"); - - // ICallHandler h1 = new Handler1(); - // ICallHandler h2 = new Handler2(); - // ICallHandler h3 = new Handler3(); - - // p.Handlers.Add(h2); - // p.Handlers.Add(h1); - // p.Handlers.Add(h3); - - // Assert.AreEqual(3, p.Handlers.Count); - // Assert.AreSame(h2, p.Handlers[0]); - // Assert.AreSame(h1, p.Handlers[1]); - // Assert.AreSame(h3, p.Handlers[2]); - //} + [TestMethod] + [Ignore] + public void ShouldInitializeToEmpty() + { + //RuleDrivenPolicy p = new RuleDrivenPolicy("Empty"); + //Assert.AreEqual("Empty", p.Name); + //Assert.AreEqual(0, p.RuleSet.Count); + //Assert.AreEqual(0, p.Handlers.Count); + } + + [TestMethod] + [Ignore] + public void ShouldPreserveHandlerOrder() + { + //RuleDrivenPolicy p = new RuleDrivenPolicy("OrderedHandlers"); + + //ICallHandler h1 = new Handler1(); + //ICallHandler h2 = new Handler2(); + //ICallHandler h3 = new Handler3(); + + //p.Handlers.Add(h2); + //p.Handlers.Add(h1); + //p.Handlers.Add(h3); + + //Assert.AreEqual(3, p.Handlers.Count); + //Assert.AreSame(h2, p.Handlers[0]); + //Assert.AreSame(h1, p.Handlers[1]); + //Assert.AreSame(h3, p.Handlers[2]); + } [TestMethod] public void ShouldHaveNoHandlersWhenPolicyDoesntMatch() { IMatchingRule[] rules = { }; - IUnityContainer container = CreateConfiguredContainer(); - - InjectionPolicy p = CreatePolicy(container, rules); + InjectionPolicy p = CreatePolicy(rules); MethodImplementationInfo thisMember = GetMethodImplInfo("ShouldHaveNoHandlersWhenPolicyDoesntMatch"); List memberHandlers - = new List(p.GetHandlersFor(thisMember, container)); + = new List(p.GetHandlersFor(thisMember, Container)); Assert.AreEqual(0, memberHandlers.Count); } @@ -67,14 +65,13 @@ List memberHandlers public void ShouldGetHandlersInOrderWithGetHandlersFor() { IMatchingRule[] rules = { new MemberNameMatchingRule("ShouldGetHandlersInOrderWithGetHandlersFor") }; - IUnityContainer container = CreateConfiguredContainer(); - InjectionPolicy p = CreatePolicy(container, rules); + InjectionPolicy p = CreatePolicy(rules); MethodImplementationInfo member = GetMethodImplInfo("ShouldGetHandlersInOrderWithGetHandlersFor"); - List expectedHandlers = new List(container.ResolveAll()); - List actualHandlers = new List(p.GetHandlersFor(member, container)); + List expectedHandlers = new List(Container.ResolveAll()); + List actualHandlers = new List(p.GetHandlersFor(member, Container)); CollectionAssertExtensions.AreEqual( expectedHandlers, @@ -86,15 +83,14 @@ public void ShouldGetHandlersInOrderWithGetHandlersFor() public void ShouldBeAbleToMatchPropertyGet() { IMatchingRule[] rules = { new MemberNameMatchingRule("get_Balance") }; - IUnityContainer container = CreateConfiguredContainer(); - InjectionPolicy p = CreatePolicy(container, rules); + InjectionPolicy p = CreatePolicy(rules); PropertyInfo balanceProperty = typeof(MockDal).GetProperty("Balance"); MethodImplementationInfo getMethod = new MethodImplementationInfo(null, balanceProperty.GetGetMethod()); - List expectedHandlers = new List(container.ResolveAll()); - List actualHandlers = new List(p.GetHandlersFor(getMethod, container)); + List expectedHandlers = new List(Container.ResolveAll()); + List actualHandlers = new List(p.GetHandlersFor(getMethod, Container)); CollectionAssertExtensions.AreEqual( expectedHandlers, @@ -102,17 +98,16 @@ public void ShouldBeAbleToMatchPropertyGet() new TypeComparer()); } - private static InjectionPolicy CreatePolicy(IUnityContainer container, IMatchingRule[] rules) + private static InjectionPolicy CreatePolicy(IMatchingRule[] rules) { InjectionPolicy p = new RuleDrivenPolicy(rules, new string[] { "handler1", "handler2", "handler3" }); return p; } - private static IUnityContainer CreateConfiguredContainer() + public override IUnityContainer GetContainer() { - IUnityContainer container = - new UnityContainer() + IUnityContainer container = base.GetContainer() .RegisterType("handler1") .RegisterType("handler2") .RegisterType("handler3"); @@ -126,6 +121,9 @@ private static MethodImplementationInfo GetMethodImplInfo(string methodName) } } + + #region Test Data + public class Handler1 : ICallHandler { private int order = 0; @@ -207,4 +205,6 @@ public int Compare(object x, object y) return -1; } } + + #endregion } diff --git a/tests/CodeplexIssuesFixture.cs b/tests/Unit/Issues/Codeplex.cs similarity index 63% rename from tests/CodeplexIssuesFixture.cs rename to tests/Unit/Issues/Codeplex.cs index 6ccb05a..53b0fa0 100644 --- a/tests/CodeplexIssuesFixture.cs +++ b/tests/Unit/Issues/Codeplex.cs @@ -1,42 +1,45 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Unity; -using Unity.Interception; using Unity.Interception.ContainerIntegration; using Unity.Interception.Interceptors; using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception; +using Unity.Interception.Tests; -namespace Microsoft.Practices.Unity.InterceptionExtension.Tests +namespace Issue.Tests { /// - /// Summary description for CodeplexIssuesFixture + /// Codeplex Issues Fixture /// [TestClass] - public class CodeplexIssuesFixture + public class Codeplex : TestFixtureBase { - public interface IRepository { } - public class TestRepository : IRepository { } - public class TestService - { - public TestService(IRepository repository) - { - } - } - [TestMethod] public void DependenciesAndInterceptionMixProperly() { - var container = new UnityContainer() - .AddNewExtension() + Container .RegisterType() - .RegisterType( - new Interceptor()); + .RegisterType(new Interceptor()); - var svc1 = container.Resolve(); - var svc2 = container.Resolve(); + var svc1 = Container.Resolve(); + var svc2 = Container.Resolve(); Assert.AreNotSame(svc1, svc2); Assert.IsNotNull(svc1 as IInterceptingProxy); Assert.IsNotNull(svc2 as IInterceptingProxy); } + + #region Test Data + + public interface IRepository { } + public class TestRepository : IRepository { } + public class TestService + { + public TestService(IRepository repository) + { + } + } + + + #endregion } } diff --git a/tests/Issues.cs b/tests/Unit/Issues/GitHub.cs similarity index 56% rename from tests/Issues.cs rename to tests/Unit/Issues/GitHub.cs index aa72d28..817cd69 100644 --- a/tests/Issues.cs +++ b/tests/Unit/Issues/GitHub.cs @@ -8,15 +8,34 @@ using Unity.Interception.InterceptionBehaviors; using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception; using Unity.Interception.PolicyInjection.Pipeline; +using Unity.Interception.Tests; using Unity.Lifetime; -namespace UnityInterception.Tests +namespace Issue.Tests { + /// + /// GitHub Issues Fixture + /// [TestClass] - public class Issues + public class GitHub : TestFixtureBase { [TestMethod] - public void unitycontainer_unity_177() + public void interception_162() + { + var container = new UnityContainer(); + container.AddNewExtension(); + container.RegisterType(new ContainerControlledLifetimeManager(), + new Interceptor(), + new InterceptionBehavior()); + + var class1 = container.Resolve(); + var class2 = container.Resolve(); + class1.MyFunction(); + class2.MyFunction(); + } + + [TestMethod] + public void container_177() { var container = new UnityContainer(); container.AddNewExtension(); @@ -28,7 +47,7 @@ public void unitycontainer_unity_177() container.RegisterType(new Interceptor(), new InterceptionBehavior()); - + MyClass.Reset(); var class1 = container.Resolve(); var class2 = container.Resolve(); class1.MyFunction(); @@ -36,9 +55,8 @@ public void unitycontainer_unity_177() Assert.AreEqual(1, MyClass.Count); } - [TestMethod] - public void unitycontainer_unity_45() + public void container_45() { var proxy = Intercept.ThroughProxy>( new Thing(), @@ -47,74 +65,64 @@ public void unitycontainer_unity_45() proxy.DoSomething("hello world"); } + } + + #region Test Data - public interface IInterface + public interface IInterface + { + TOut DoSomething(TIn input); + } + + public class Thing : IInterface + { + public string DoSomething(string input) { - TOut DoSomething(TIn input); + return input; } + } - public class Thing : IInterface + public class TestInterceptor : IInterceptionBehavior + { + public bool WillExecute => true; + + public IEnumerable GetRequiredInterfaces() { - public string DoSomething(string input) - { - return input; - } + return Type.EmptyTypes; } - public class TestInterceptor : IInterceptionBehavior + public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { - public bool WillExecute => true; - - public IEnumerable GetRequiredInterfaces() - { - return Type.EmptyTypes; - } - - public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) - { - return getNext()(input, null); - } + return getNext()(input, null); } + } + public interface IMyClass { void MyFunction(); } - [TestMethod] - public void unitycontainer_interception_162() - { - var container = new UnityContainer(); - container.AddNewExtension(); - container.RegisterType(new ContainerControlledLifetimeManager(), - new Interceptor(), - new InterceptionBehavior()); + public interface IMyOtherClass { void MyFunction(); } - var class1 = container.Resolve(); - var class2 = container.Resolve(); - class1.MyFunction(); - class2.MyFunction(); - } + public class MyClass : IMyClass, IMyOtherClass + { + public static int Count = 0; - public interface IMyClass { void MyFunction(); } + public MyClass() { Count++; } - public interface IMyOtherClass { void MyFunction(); } + public void MyFunction() { Debug.WriteLine("MyFunction"); } - public class MyClass : IMyClass, IMyOtherClass - { - public static int Count = 0; - - public MyClass() { Count++; } + public static void Reset() => Count = 0; + } - public void MyFunction() { Debug.WriteLine("MyFunction"); } - } - public class LoggingInterceptionBehavior : IInterceptionBehavior + public class LoggingInterceptionBehavior : IInterceptionBehavior + { + public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { - public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) - { - Debug.WriteLine("Logging before the Function!! yeah, i like it!"); - return getNext()(input, getNext); - } - - public bool WillExecute => true; - public IEnumerable GetRequiredInterfaces() { return Type.EmptyTypes; } + Debug.WriteLine("Logging before the Function!! yeah, i like it!"); + return getNext()(input, getNext); } + public bool WillExecute => true; + public IEnumerable GetRequiredInterfaces() { return Type.EmptyTypes; } } + + #endregion } diff --git a/tests/Unit/Standalone/AddInterfaceThroughProxy.cs b/tests/Unit/Standalone/AddInterfaceThroughProxy.cs new file mode 100644 index 0000000..a45acc3 --- /dev/null +++ b/tests/Unit/Standalone/AddInterfaceThroughProxy.cs @@ -0,0 +1,75 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Unity.Interception; +using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception; +using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception; +using Unity.Interception.Tests; + +namespace Standalone.Tests +{ + [TestClass] + public class AddInterfaceThroughProxy + { + [TestMethod] + public void CanProxyWithBehaviorThatAddsInterface() + { + // Arrange + var target = new MockDal(); + + // Act + var proxied = Intercept.ThroughProxy(target, new InterfaceInterceptor(), new[] { new AdditionalInterfaceBehavior() }); + + // Validate + Assert.IsNotNull(proxied); + } + + [TestMethod] + public void BehaviorAddsInterface() + { + // Arrange + var target = new MockDal(); + + // Act + var proxied = Intercept.ThroughProxy(target, new InterfaceInterceptor(), new[] { new AdditionalInterfaceBehavior() }); + + // Validate + Assert.IsNotNull(proxied as IAdditionalInterface); + } + + [TestMethod] + public void CanInvokeMethodAddedByBehavior() + { + // Act + var proxied = Intercept.NewInstance( new VirtualMethodInterceptor(), new[] { new AdditionalInterfaceBehavior() }); + + // Validate + Assert.AreEqual(10, ((IAdditionalInterface)proxied).DoNothing()); + } + + [TestMethod] + public void CanManuallyAddAdditionalInterface() + { + // Arrange + var target = new MockDal(); + + // Act + var proxied = Intercept.ThroughProxyWithAdditionalInterfaces(target, new InterfaceInterceptor(), new[] { new AdditionalInterfaceBehavior(false) }, + new[] { typeof(IAdditionalInterface) }); + + // Validate + Assert.IsNotNull(proxied as IAdditionalInterface); + } + + [TestMethod] + public void CanInvokeMethodOnManuallyAddedInterface() + { + // Arrange + var target = new MockDal(); + + // Act + var proxied = Intercept.ThroughProxyWithAdditionalInterfaces(target, new InterfaceInterceptor(), new[] { new AdditionalInterfaceBehavior(false) }, + new[] { typeof(IAdditionalInterface) }); + // Validate + Assert.AreEqual(10, ((IAdditionalInterface)proxied).DoNothing()); + } + } +} diff --git a/tests/InterceptFixture.cs b/tests/Unit/Standalone/InterceptFixture.cs similarity index 98% rename from tests/InterceptFixture.cs rename to tests/Unit/Standalone/InterceptFixture.cs index 2de9614..b797931 100644 --- a/tests/InterceptFixture.cs +++ b/tests/Unit/Standalone/InterceptFixture.cs @@ -1,9 +1,6 @@ - - +using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; -using Microsoft.Practices.Unity.TestSupport; -using Microsoft.VisualStudio.TestTools.UnitTesting; using Unity.Interception; using Unity.Interception.InterceptionBehaviors; using Unity.Interception.Interceptors; @@ -11,8 +8,9 @@ using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception; using Unity.Interception.Interceptors.TypeInterceptors; using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception; +using Unity.Interception.Tests; -namespace Microsoft.Practices.Unity.InterceptionExtension.Tests +namespace Standalone.Tests { [TestClass] public class InterceptFixture diff --git a/tests/TransparentProxyInterception/InterceptingRealProxyFixture.cs b/tests/Unit/Standalone/InterceptingRealProxyFixture.cs similarity index 92% rename from tests/TransparentProxyInterception/InterceptingRealProxyFixture.cs rename to tests/Unit/Standalone/InterceptingRealProxyFixture.cs index 305ac13..2ce877a 100644 --- a/tests/TransparentProxyInterception/InterceptingRealProxyFixture.cs +++ b/tests/Unit/Standalone/InterceptingRealProxyFixture.cs @@ -1,13 +1,11 @@ - - -using System; +using System; using System.ComponentModel; -using Microsoft.Practices.Unity.TestSupport; using Microsoft.VisualStudio.TestTools.UnitTesting; using Unity.Interception.Interceptors; using Unity.Interception.Interceptors.InstanceInterceptors.TransparentProxyInterception; +using Unity.Interception.Tests; -namespace Microsoft.Practices.Unity.InterceptionExtension.TransparaentProxyInterception.Tests +namespace Standalone.Tests { [TestClass] public class InterceptingRealProxyFixture @@ -97,19 +95,19 @@ public void CanCreateProxyWithAdditionalInterfaces() { MBROWithOneMethod original = new MBROWithOneMethod(); MBROWithOneMethod proxy = - new InterceptingRealProxy(original, typeof(MBROWithOneMethod), typeof(InterfaceOne)) + new InterceptingRealProxy(original, typeof(MBROWithOneMethod), typeof(IInterfaceOne)) .GetTransparentProxy() as MBROWithOneMethod; - Assert.IsTrue(proxy is InterfaceOne); + Assert.IsTrue(proxy is IInterfaceOne); } [TestMethod] public void InvokingMethodOnAdditionalInterfaceThrowsIfNotHandledByInterceptor() { MBROWithOneMethod original = new MBROWithOneMethod(); - InterfaceOne proxy = - new InterceptingRealProxy(original, typeof(MBROWithOneMethod), typeof(InterfaceOne)) - .GetTransparentProxy() as InterfaceOne; + IInterfaceOne proxy = + new InterceptingRealProxy(original, typeof(MBROWithOneMethod), typeof(IInterfaceOne)) + .GetTransparentProxy() as IInterfaceOne; try { @@ -126,9 +124,9 @@ public void InvokingMethodOnAdditionalInterfaceThrowsIfNotHandledByInterceptor() public void CanSuccessfullyInvokeAnAdditionalInterfaceMethodIfAnInterceptorDoesNotForwardTheCall() { MBROWithOneMethod original = new MBROWithOneMethod(); - InterfaceOne proxy = - new InterceptingRealProxy(original, typeof(MBROWithOneMethod), typeof(InterfaceOne)) - .GetTransparentProxy() as InterfaceOne; + IInterfaceOne proxy = + new InterceptingRealProxy(original, typeof(MBROWithOneMethod), typeof(IInterfaceOne)) + .GetTransparentProxy() as IInterfaceOne; bool invoked = false; ((IInterceptingProxy)proxy).AddInterceptionBehavior( new DelegateInterceptionBehavior( @@ -149,7 +147,7 @@ public void CanImplementINotifyPropertyChanged() ((IInterceptingProxy)proxy).AddInterceptionBehavior(new NaiveINotifyPropertyChangedInterceptionBehavior()); string changeProperty; - PropertyChangedEventHandler handler = (sender, args) => changeProperty = args.PropertyName; + void handler(object sender, PropertyChangedEventArgs args) => changeProperty = args.PropertyName; changeProperty = null; ((INotifyPropertyChanged)proxy).PropertyChanged += handler; @@ -178,7 +176,7 @@ public void CanImplementINotifyPropertyChangedThroughInterface() ((IInterceptingProxy)proxy).AddInterceptionBehavior(new NaiveINotifyPropertyChangedInterceptionBehavior()); string changeProperty; - PropertyChangedEventHandler handler = (sender, args) => changeProperty = args.PropertyName; + void handler(object sender, PropertyChangedEventArgs args) => changeProperty = args.PropertyName; changeProperty = null; ((INotifyPropertyChanged)proxy).PropertyChanged += handler; @@ -207,7 +205,7 @@ public void CanImplementINotifyPropertyChangedThroughExplicitInterface() ((IInterceptingProxy)proxy).AddInterceptionBehavior(new NaiveINotifyPropertyChangedInterceptionBehavior()); string changeProperty; - PropertyChangedEventHandler handler = (sender, args) => changeProperty = args.PropertyName; + void handler(object sender, PropertyChangedEventArgs args) => changeProperty = args.PropertyName; changeProperty = null; ((INotifyPropertyChanged)proxy).PropertyChanged += handler; @@ -244,6 +242,9 @@ public void CanInterceptGenericMethodOnInterface() Assert.AreEqual(1, interceptor.CallCount); } + + #region Test Data + internal class MBROWithOneMethod : MarshalByRefObject { public int DoSomething(int i) @@ -252,12 +253,12 @@ public int DoSomething(int i) } } - internal interface InterfaceOne + internal interface IInterfaceOne { void Something(); } - internal class MBROWithInterface : MarshalByRefObject, InterfaceOne + internal class MBROWithInterface : MarshalByRefObject, IInterfaceOne { public void Something() { @@ -310,5 +311,7 @@ public string GetTypeName(T argument) #endregion } + + #endregion } } diff --git a/tests/InterfaceInterception/InterfaceInterceptorFixture.Desktop.cs b/tests/Unit/Unit/InterfaceInterceptor.Desktop.cs similarity index 88% rename from tests/InterfaceInterception/InterfaceInterceptorFixture.Desktop.cs rename to tests/Unit/Unit/InterfaceInterceptor.Desktop.cs index 5c79cc5..360fc2d 100644 --- a/tests/InterfaceInterception/InterfaceInterceptorFixture.Desktop.cs +++ b/tests/Unit/Unit/InterfaceInterceptor.Desktop.cs @@ -1,18 +1,15 @@ - - +using Microsoft.Practices.Unity.TestSupport; +using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Proxies; -using System.Text; -using Microsoft.Practices.Unity.TestSupport; -using Microsoft.VisualStudio.TestTools.UnitTesting; using Unity.Interception.Interceptors; using Unity.Interception.Interceptors.InstanceInterceptors; using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception; +using Unity.Interception.Tests; -namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.InterfaceInterception +namespace Unit.Tests { public partial class InterfaceInterceptorFixture { @@ -50,8 +47,8 @@ public void CanGetInterceptableMethodsForProxy() private class MyProxy : RealProxy { - private Type t; - private object impl; + private readonly Type t; + private readonly object impl; public MyProxy(Type t, object impl) : base(t) @@ -62,8 +59,7 @@ public MyProxy(Type t, object impl) public override IMessage Invoke(IMessage msg) { - IMethodCallMessage method = msg as IMethodCallMessage; - if (method != null) + if (msg is IMethodCallMessage method) { if (method.MethodName == "GetType") { diff --git a/tests/InterfaceInterception/InterfaceInterceptorFixture.cs b/tests/Unit/Unit/InterfaceInterceptor.cs similarity index 88% rename from tests/InterfaceInterception/InterfaceInterceptorFixture.cs rename to tests/Unit/Unit/InterfaceInterceptor.cs index 7c0a10a..279da99 100644 --- a/tests/InterfaceInterception/InterfaceInterceptorFixture.cs +++ b/tests/Unit/Unit/InterfaceInterceptor.cs @@ -1,4 +1,5 @@ -using Microsoft.Practices.Unity.InterceptionExtension.Tests.MatchingRules; +using Microsoft.Practices.Unity.InterceptionExtension.Tests; +using Microsoft.Practices.Unity.InterceptionExtension.Tests.MatchingRules; using Microsoft.Practices.Unity.InterceptionExtension.Tests.ObjectsUnderTest; using Microsoft.Practices.Unity.TestSupport; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -18,10 +19,10 @@ using Unity.Interception.PolicyInjection.MatchingRules; using Unity.Interception.PolicyInjection.Pipeline; using Unity.Interception.PolicyInjection.Policies; -using Unity.Interception.Utilities; +using Unity.Interception.Tests; using Unity.Lifetime; -namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.InterfaceInterception +namespace Unit.Tests { [TestClass] public partial class InterfaceInterceptorFixture @@ -29,14 +30,14 @@ public partial class InterfaceInterceptorFixture [TestMethod] public void InterceptorDoesNotInterceptClass() { - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); Assert.IsFalse(interceptor.CanIntercept(GetType())); } [TestMethod] public void InterceptorCanInterceptInterface() { - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); Assert.IsTrue(interceptor.CanIntercept(typeof(IMatchingRule))); } @@ -46,9 +47,9 @@ public void InterceptorReturnsCorrectMethodsForInterceptableType() List methods = new InterfaceInterceptor().GetInterceptableMethods(typeof(IInterfaceOne), typeof(ImplementationOne)).ToList(); - List expected = Sequence.Collect( + List expected = new MethodImplementationInfo[] { new MethodImplementationInfo(typeof(IInterfaceOne).GetMethod("TargetMethod"), - typeof(ImplementationOne).GetMethod("TargetMethod"))).ToList(); + typeof(ImplementationOne).GetMethod("TargetMethod")) }.ToList(); CollectionAssertExtensions.AreEquivalent(expected, methods); } @@ -60,11 +61,11 @@ public void InterceptorIncludesMethodsFromBaseInterfaceForInterface() new InterfaceInterceptor().GetInterceptableMethods(typeof(Interface), typeof(Interface)).ToList(); - List expected = Sequence.Collect( + List expected = new MethodImplementationInfo[] { new MethodImplementationInfo(typeof(Interface).GetMethod("Method"), typeof(Interface).GetMethod("Method")), new MethodImplementationInfo(typeof(InterfaceBase).GetMethod("Method3"), - typeof(InterfaceBase).GetMethod("Method3"))) + typeof(InterfaceBase).GetMethod("Method3")) } .ToList(); CollectionAssertExtensions.AreEquivalent(expected, methods); @@ -77,11 +78,11 @@ public void InterceptorIncludesMethodsFromBaseInterfaceForInterceptableType() new InterfaceInterceptor().GetInterceptableMethods(typeof(Interface), typeof(WrappableThroughInterface)).ToList(); - List expected = Sequence.Collect( + List expected = new MethodImplementationInfo[] { new MethodImplementationInfo(typeof(Interface).GetMethod("Method"), typeof(WrappableThroughInterface).GetMethod("Method")), new MethodImplementationInfo(typeof(InterfaceBase).GetMethod("Method3"), - typeof(WrappableThroughInterface).GetMethod("Method3"))) + typeof(WrappableThroughInterface).GetMethod("Method3")) } .ToList(); CollectionAssertExtensions.AreEquivalent(expected, methods); @@ -103,7 +104,7 @@ public void InterceptorMapsGenericMethodsOnClosedGenericInterfaces() [TestMethod] public void InterceptorCreatesProxyInstance() { - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); ImplementsInterfaceOne target = new ImplementsInterfaceOne(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IInterfaceOne), target); @@ -117,7 +118,7 @@ public void InterceptorCreatesProxyInstance() [TestMethod] public void GeneratedProxyCallsInterceptionBehaviors() { - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); ImplementsInterfaceOne target = new ImplementsInterfaceOne(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IInterfaceOne), target); @@ -136,7 +137,7 @@ public void GeneratedProxyCallsInterceptionBehaviors() [TestMethod] public void ParametersPassProperlyToTarget() { - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); MyDal target = new MyDal(); CallCountHandler depositHandler = new CallCountHandler(); @@ -167,7 +168,7 @@ public void ParametersPassProperlyToTarget() [TestMethod] public void CanGenerateProxyForClosedGeneric() { - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); GenericImplementationOne target = new GenericImplementationOne(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IGenericOne), target); @@ -187,7 +188,7 @@ public void CanGenerateProxyForClosedGeneric() [TestMethod] public void RefsAndOutsAreProperlyHandled() { - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); ImplementsHaveSomeRefsAndOuts target = new ImplementsHaveSomeRefsAndOuts(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IHaveSomeRefsAndOuts), target); @@ -195,10 +196,9 @@ public void RefsAndOutsAreProperlyHandled() proxy.AddInterceptionBehavior(interceptionBehavior); IHaveSomeRefsAndOuts intercepted = (IHaveSomeRefsAndOuts)proxy; - - int a; string s = "something"; - intercepted.DoSomething(out a, ref s); + + intercepted.DoSomething(out int a, ref s); Assert.AreEqual(37, a); Assert.AreEqual("+++something***", s); @@ -208,7 +208,7 @@ public void RefsAndOutsAreProperlyHandled() [TestMethod] public void AssortedParameterKindsAreProperlyHandled() { - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); AssortedParameterKindsAreProperlyHandledHelper.TypeWithAssertedParameterKinds target = new AssortedParameterKindsAreProperlyHandledHelper.TypeWithAssertedParameterKinds(); @@ -223,7 +223,7 @@ public void AssortedParameterKindsAreProperlyHandled() [TestMethod] public void ReflectingOverProxyTypeReturnsProperties() { - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IHaveSomeProperties), target); @@ -236,7 +236,7 @@ public void ReflectingOverProxyTypeReturnsProperties() [TestMethod] public void ProxyInterceptsEvents() { - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); ClassWithEvents target = new ClassWithEvents(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IDoEvents), target); CallCountInterceptionBehavior interceptionBehavior = new CallCountInterceptionBehavior(); @@ -251,7 +251,7 @@ public void ProxyInterceptsEvents() public void ProxySendsOriginalWhenRaisingEvent() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); ClassWithEvents target = new ClassWithEvents(); IInterceptingProxy proxy = interceptor.CreateProxy(typeof(IDoEvents), target); CallCountInterceptionBehavior interceptionBehavior = new CallCountInterceptionBehavior(); @@ -288,7 +288,7 @@ public void CanInterceptDerivedInterface() container.AddNewExtension() .Configure() - .SetDefaultInterceptorFor(new InterfaceInterceptor()); + .SetDefaultInterceptorFor(new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor()); var svc = container.Resolve(); svc.Save(new Order()); @@ -491,7 +491,7 @@ public interface IInterfaceTwo public void CanCreateProxyForMultipleInterfaces() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -506,7 +506,7 @@ public void CanCreateProxyForMultipleInterfaces() public void InvokingMethodOnAdditionalInterfaceThrowsIfNotHandledByInterceptor() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); object proxy = interceptor.CreateProxy(typeof(IHaveSomeProperties), target, typeof(IInterfaceOne)); @@ -530,7 +530,7 @@ public void InvokingMethodOnAdditionalInterfaceThrowsIfNotHandledByInterceptor() public void CanSuccessfullyInvokeAnAdditionalInterfaceMethodIfAnInterceptorDoesNotForwardTheCall() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); object proxy = interceptor.CreateProxy(typeof(IHaveSomeProperties), target, typeof(IInterfaceOne)); bool invoked = false; @@ -548,11 +548,11 @@ public void CanSuccessfullyInvokeAnAdditionalInterfaceMethodIfAnInterceptorDoesN [TestMethod] public void CanImplementINotifyPropertyChanged() { - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); object proxy = interceptor.CreateProxy(typeof(IHaveSomeProperties), target, typeof(INotifyPropertyChanged)); string changeProperty = null; - PropertyChangedEventHandler handler = (sender, args) => changeProperty = args.PropertyName; + void handler(object sender, PropertyChangedEventArgs args) => changeProperty = args.PropertyName; ((IInterceptingProxy)proxy).AddInterceptionBehavior(new NaiveINotifyPropertyChangedInterceptionBehavior()); ((INotifyPropertyChanged)proxy).PropertyChanged += handler; @@ -575,7 +575,7 @@ public void CanImplementINotifyPropertyChanged() public void ProxiedInterfaceIsImplementedImplicitly() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -590,7 +590,7 @@ public void ProxiedInterfaceIsImplementedImplicitly() public void AdditionalInterfaceIsImplementedExplicitly() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -605,7 +605,7 @@ public void AdditionalInterfaceIsImplementedExplicitly() public void CanImplementMultipleInterfacesWithSameMethodSignatures() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); BaseInterfaceImplementation target = new BaseInterfaceImplementation(); object proxy = interceptor.CreateProxy(typeof(IBaseInterface), target, typeof(IBaseInterface2)); object[] returnValues = new object[] { this, "return value" }; @@ -630,7 +630,7 @@ public void CanImplementMultipleInterfacesWithSameMethodSignatures() public void CanImplementMultipleAdditionalInterfacesWithCommonAncestors() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -651,7 +651,7 @@ public void CanImplementMultipleAdditionalInterfacesWithCommonAncestors() public void CanImplementAdditionalClosedGenericInterface() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -670,7 +670,7 @@ public void CanImplementAdditionalClosedGenericInterface() public void CanImplementAdditionalClosedGenericInterfaceMultipleTimesWithDifferentParameters() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -691,7 +691,7 @@ public void CanImplementAdditionalClosedGenericInterfaceMultipleTimesWithDiffere public void SupplyingOpenGenericInterfacesAsAdditionalInterfacesThrows() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -717,7 +717,7 @@ public void SupplyingOpenGenericInterfacesAsAdditionalInterfacesThrows() public void SupplyingNonInterfacesAsAdditionalInterfacesThrows() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -743,7 +743,7 @@ public void SupplyingNonInterfacesAsAdditionalInterfacesThrows() public void SupplyingNullInterfacesAsAdditionalInterfacesThrows() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -769,7 +769,7 @@ public void SupplyingNullInterfacesAsAdditionalInterfacesThrows() public void SupplyingANullArrayOfAdditionalInterfacesThrows() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -823,7 +823,7 @@ public object TargetMethod() public void MultipleProxiesForTheSameInterfaceHaveTheSameType() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -838,7 +838,7 @@ public void MultipleProxiesForTheSameInterfaceHaveTheSameType() public void ProxiesForTheSameInterfaceButDifferentAdditionalInterfacesDoNotHaveTheSameType() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -855,7 +855,7 @@ public void ProxiesForTheSameInterfaceButDifferentAdditionalInterfacesDoNotHaveT public void ProxiesForTheSameAdditionalInterfacesButInDifferentOrderDoNotHaveTheSameType() { // arrange - IInstanceInterceptor interceptor = new InterfaceInterceptor(); + IInstanceInterceptor interceptor = new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(); HasSomeProperties target = new HasSomeProperties(); // act @@ -884,7 +884,7 @@ public void InterfaceInterceptorSetsTargetToTargetObject() var actualTarget = new ImplementsInterfaceOne(); var proxy = Intercept.ThroughProxy( - actualTarget, new InterfaceInterceptor(), + actualTarget, new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.TargetMethod(); @@ -906,7 +906,7 @@ public void CanInterceptInterfaceWithGenericMethod() }); var proxy = Intercept.ThroughProxy( - target, new InterfaceInterceptor(), + target, new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.DoSomething(); @@ -1027,7 +1027,7 @@ public void CanInterceptGenericInterfaceWithInterfaceConstraint() }); var proxy = Intercept.ThroughProxy>( - target, new InterfaceInterceptor(), + target, new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.SomeMethod(); @@ -1051,7 +1051,7 @@ public void CanInterceptNonGenericMethodOnNonGenericInterface() var proxy = Intercept.ThroughProxy( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.NonGenericMethod(null, null); @@ -1079,7 +1079,7 @@ public void CanInterceptGenericMethodOnNonGenericInterface() var proxy = Intercept.ThroughProxy( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.GenericMethod(null, null); @@ -1107,7 +1107,7 @@ public void CanInterceptGenericMethodWithConstraintOnNonGenericInterface() var proxy = Intercept.ThroughProxy( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.GenericMethodWithConstraints(null, null); @@ -1135,7 +1135,7 @@ public void CanInterceptNonGenericMethodOnGenericInterface() var proxy = Intercept.ThroughProxy>( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.NonGenericMethod(null, null); @@ -1163,7 +1163,7 @@ public void CanInterceptGenericMethodOnGenericInterface() var proxy = Intercept.ThroughProxy>( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.GenericMethod(null, null); @@ -1191,7 +1191,7 @@ public void CanInterceptGenericMethodOnGenericInterfaceUsingValueType() var proxy = Intercept.ThroughProxy>( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); var result = proxy.GenericMethodDifferentReturnType(100, null); @@ -1220,7 +1220,7 @@ public void CanInterceptGenericMethodWithConstraintOnGenericInterface() var proxy = Intercept.ThroughProxy>( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.GenericMethodWithConstraints(null, null); @@ -1248,7 +1248,7 @@ public void CanInterceptGenericMethodWithConstraintRelatedToInterfaceOnGenericIn var proxy = Intercept.ThroughProxy>( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.GenericMethodWithConstraintsOnTheInterfaceParameter(null, null); @@ -1276,7 +1276,7 @@ public void CanInterceptNonGenericMethodOnGenericInterfaceWithConstraint() var proxy = Intercept.ThroughProxy>( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.NonGenericMethod(null, null); @@ -1304,7 +1304,7 @@ public void CanInterceptGenericMethodOnGenericInterfaceWithConstraint() var proxy = Intercept.ThroughProxy>( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.GenericMethod(null, null); @@ -1332,7 +1332,7 @@ public void CanInterceptGenericMethodWithConstraintOnGenericInterfaceWithConstra var proxy = Intercept.ThroughProxy>( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.GenericMethodWithConstraints(null, null); @@ -1360,7 +1360,7 @@ public void CanInterceptGenericMethodWithConstraintRelatedToInterfaceOnGenericIn var proxy = Intercept.ThroughProxy>( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.GenericMethodWithConstraintsOnTheInterfaceParameter(null, null); @@ -1415,12 +1415,12 @@ public string NonGenericMethod(IEnumerable param1, string param2) public T GenericMethod(IEnumerable param1, T param2) { - return default(T); + return default; } public T GenericMethodWithConstraints(IEnumerable param1, T param2) where T : class { - return default(T); + return default; } } @@ -1433,19 +1433,21 @@ public string NonGenericMethod(T1 param1, string param2) public T GenericMethod(T1 param1, T param2) { +#pragma warning disable IDE0059 // Unnecessary assignment of a value var handle = MethodBase.GetCurrentMethod().MethodHandle; +#pragma warning restore IDE0059 // Unnecessary assignment of a value - return default(T); + return default; } public T GenericMethodWithConstraints(T1 param1, T param2) where T : class { - return default(T); + return default; } public T GenericMethodWithConstraintsOnTheInterfaceParameter(T1 param1, T param2) where T : T1 { - return default(T); + return default; } public T1 GenericMethodDifferentReturnType(T1 param1, T param2) @@ -1464,17 +1466,17 @@ public string NonGenericMethod(T1 param1, string param2) public T GenericMethod(T1 param1, T param2) { - return default(T); + return default; } public T GenericMethodWithConstraints(T1 param1, T param2) where T : class { - return default(T); + return default; } public T GenericMethodWithConstraintsOnTheInterfaceParameter(T1 param1, T param2) where T : T1 { - return default(T); + return default; } } @@ -1494,7 +1496,7 @@ public void CanInterceptConstrainedInheritedInterfaceMethod() var proxy = Intercept.ThroughProxy( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.Test>(); @@ -1513,7 +1515,7 @@ public class BaseGenericClass : IBaseGenericInterface { public virtual TDerivedType Test() where TDerivedType : TBaseType { - return default(TDerivedType); + return default; } } @@ -1541,7 +1543,7 @@ public void CanInterceptConstrainedInheritedInterfaceMethod2() var proxy = Intercept.ThroughProxy>>( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); proxy.TestMethod, DerivedType>( @@ -1581,7 +1583,7 @@ public Za TestMethod(BaseType a, IEnumerable b, IEnumerable>( target, - new InterfaceInterceptor(), + new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor(), new[] { behavior }); invocation = null; @@ -1655,7 +1657,7 @@ public KeyValuePair>[]> Test(ISet[] p1, M where M1 : ISet where M2 : IEnumerable { - return default(KeyValuePair>[]>); + return default; } public int CompareTo(object obj) @@ -1676,7 +1678,7 @@ public void InterceptorCorrectlyRethrowsException() .AddNewExtension() .RegisterType(typeof(IFoo), typeof(Foo)) .Configure() - .SetInterceptorFor(typeof(IFoo), new InterfaceInterceptor()) + .SetInterceptorFor(typeof(IFoo), new Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception.InterfaceInterceptor()) .AddPolicy("AlwaysMatches") .AddMatchingRule() .AddCallHandler("callCount", new ContainerControlledLifetimeManager()) diff --git a/tests/MatchingRuleSetFixture.cs b/tests/Unit/Unit/MatchingRuleSetFixture.cs similarity index 58% rename from tests/MatchingRuleSetFixture.cs rename to tests/Unit/Unit/MatchingRuleSetFixture.cs index 624f3cc..28c2ac1 100644 --- a/tests/MatchingRuleSetFixture.cs +++ b/tests/Unit/Unit/MatchingRuleSetFixture.cs @@ -1,10 +1,8 @@ - - -using System.Reflection; +using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; using Unity.Interception.PolicyInjection.MatchingRules; -namespace Microsoft.Practices.Unity.InterceptionExtension.Tests +namespace Unit.Tests { /// /// Tests for the MatchingRuleSet class @@ -17,26 +15,29 @@ public void ShouldNotMatchWithNoContainedRules() { MatchingRuleSet ruleSet = new MatchingRuleSet(); - MethodBase member = GetType().GetMethod("ShouldNotMatchWithNoContainedRules"); + MethodBase member = GetType().GetMethod(nameof(ShouldNotMatchWithNoContainedRules)); Assert.IsFalse(ruleSet.Matches(member)); } [TestMethod] public void ShouldMatchWithMatchingTypeRule() { - MatchingRuleSet ruleSet = new MatchingRuleSet(); - ruleSet.Add(new TypeMatchingRule(typeof(MatchingRuleSetFixture))); - MethodBase member = GetType().GetMethod("ShouldMatchWithMatchingTypeRule"); + MatchingRuleSet ruleSet = new MatchingRuleSet + { + new TypeMatchingRule(typeof(MatchingRuleSetFixture)) + }; + MethodBase member = GetType().GetMethod(nameof(ShouldMatchWithMatchingTypeRule)); Assert.IsTrue(ruleSet.Matches(member)); } [TestMethod] public void ShouldNotMatchWhenOneRuleDoesntMatch() { - MethodBase member = GetType().GetMethod("ShouldNotMatchWhenOneRuleDoesntMatch"); - MatchingRuleSet ruleSet = new MatchingRuleSet(); - - ruleSet.Add(new TypeMatchingRule(typeof(MatchingRuleSetFixture))); + MethodBase member = GetType().GetMethod(nameof(ShouldNotMatchWhenOneRuleDoesntMatch)); + MatchingRuleSet ruleSet = new MatchingRuleSet + { + new TypeMatchingRule(typeof(MatchingRuleSetFixture)) + }; Assert.IsTrue(ruleSet.Matches(member)); ruleSet.Add(new MemberNameMatchingRule("ThisMethodDoesntExist")); diff --git a/tests/Unit/Unity.Interception.Tests.csproj b/tests/Unit/Unity.Interception.Tests.csproj new file mode 100644 index 0000000..6fb29f3 --- /dev/null +++ b/tests/Unit/Unity.Interception.Tests.csproj @@ -0,0 +1,19 @@ + + + + Unity.Interception.Tests + false + net48 + + + + + + + + + + + + + diff --git a/tests/AssortedParameterKindsAreProperlyHandledHelper.Desktop.cs b/tests/Unit/WorkInProgress/AssortedParameterKindsAreProperlyHandledHelper.Desktop.cs similarity index 100% rename from tests/AssortedParameterKindsAreProperlyHandledHelper.Desktop.cs rename to tests/Unit/WorkInProgress/AssortedParameterKindsAreProperlyHandledHelper.Desktop.cs diff --git a/tests/AssortedParameterKindsAreProperlyHandledHelper.cs b/tests/Unit/WorkInProgress/AssortedParameterKindsAreProperlyHandledHelper.cs similarity index 100% rename from tests/AssortedParameterKindsAreProperlyHandledHelper.cs rename to tests/Unit/WorkInProgress/AssortedParameterKindsAreProperlyHandledHelper.cs diff --git a/tests/AttributeDrivenPolicyFixture.cs b/tests/Unit/WorkInProgress/AttributeDrivenPolicyFixture.cs similarity index 95% rename from tests/AttributeDrivenPolicyFixture.cs rename to tests/Unit/WorkInProgress/AttributeDrivenPolicyFixture.cs index 622bcfa..d0bb149 100644 --- a/tests/AttributeDrivenPolicyFixture.cs +++ b/tests/Unit/WorkInProgress/AttributeDrivenPolicyFixture.cs @@ -1,15 +1,12 @@ - - +using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections; using System.Collections.Generic; -using Microsoft.VisualStudio.TestTools.UnitTesting; using Unity; using Unity.Interception.Interceptors; using Unity.Interception.PolicyInjection.MatchingRules; using Unity.Interception.PolicyInjection.Pipeline; using Unity.Interception.PolicyInjection.Policies; -using Unity.Interception.Utilities; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests { @@ -44,10 +41,10 @@ public void Setup() hasAttributeMethod = MakeMethodImpl("HasAttribute"); doesntHaveAttributeMethod = MakeMethodImpl("DoesntHaveAttribute"); newMethod = MakeMethodImpl("ANewMethod"); - getNewNameMethod = new MethodImplementationInfo(null, StaticReflection.GetPropertyGetMethodInfo((DerivedAttributeTestTarget t) => t.Name)); + getNewNameMethod = new MethodImplementationInfo(null, typeof(DerivedAttributeTestTarget).GetProperty(nameof(DerivedAttributeTestTarget.Name)).GetGetMethod()); - getItemMethod = new MethodImplementationInfo(null, StaticReflection.GetPropertyGetMethodInfo((DerivedAttributeTestTarget t) => t.Item)); - setItemMethod = new MethodImplementationInfo(null, StaticReflection.GetPropertySetMethodInfo((DerivedAttributeTestTarget t) => t.Item)); + getItemMethod = new MethodImplementationInfo(null, typeof(DerivedAttributeTestTarget).GetProperty(nameof(DerivedAttributeTestTarget.Item), new Type[0]).GetGetMethod()); + setItemMethod = new MethodImplementationInfo(null, typeof(DerivedAttributeTestTarget).GetProperty(nameof(DerivedAttributeTestTarget.Item), new Type[0]).GetSetMethod()); getItemIntMethod = new MethodImplementationInfo(null, typeof(DerivedAttributeTestTarget).GetMethod("get_Item", new[] { typeof(int) })); setItemIntMethod = new MethodImplementationInfo(null, typeof(DerivedAttributeTestTarget).GetMethod("set_Item", new[] { typeof(int), typeof(object) })); @@ -272,16 +269,17 @@ public string Name } [CallHandler3] - public string DoSomething(string key, - int value) + public string DoSomething(string key, int value) { - return "I did something"; + return $"I did something with key: '{key}' and value: '{value}'"; } +#pragma warning disable IDE0060 // Remove unused parameter public int GetCriticalInformation(string key) { return 42; } +#pragma warning restore IDE0060 // Remove unused parameter [ApplyNoPolicies] public void MustBeFast() { } diff --git a/tests/ConvenienceConfigurationFixture.cs b/tests/Unit/WorkInProgress/ConvenienceConfigurationFixture.cs similarity index 99% rename from tests/ConvenienceConfigurationFixture.cs rename to tests/Unit/WorkInProgress/ConvenienceConfigurationFixture.cs index cc99f3c..67cf710 100644 --- a/tests/ConvenienceConfigurationFixture.cs +++ b/tests/Unit/WorkInProgress/ConvenienceConfigurationFixture.cs @@ -9,6 +9,7 @@ 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 diff --git a/tests/EventInterceptionFixture.cs b/tests/Unit/WorkInProgress/EventInterceptionFixture.cs similarity index 96% rename from tests/EventInterceptionFixture.cs rename to tests/Unit/WorkInProgress/EventInterceptionFixture.cs index 574d502..5db17fb 100644 --- a/tests/EventInterceptionFixture.cs +++ b/tests/Unit/WorkInProgress/EventInterceptionFixture.cs @@ -1,5 +1,4 @@ -using Microsoft.Practices.Unity.TestSupport; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using Unity; using Unity.Interception; @@ -8,6 +7,7 @@ using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception; using Unity.Interception.PolicyInjection; using Unity.Interception.PolicyInjection.Pipeline; +using Unity.Interception.Tests; using Unity.Lifetime; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests diff --git a/tests/FakeObjects/FakeInterceptionBehavior.cs b/tests/Unit/WorkInProgress/FakeObjects/FakeInterceptionBehavior.cs similarity index 100% rename from tests/FakeObjects/FakeInterceptionBehavior.cs rename to tests/Unit/WorkInProgress/FakeObjects/FakeInterceptionBehavior.cs diff --git a/tests/FakeObjects/FakeMethodCallMessage.cs b/tests/Unit/WorkInProgress/FakeObjects/FakeMethodCallMessage.cs similarity index 100% rename from tests/FakeObjects/FakeMethodCallMessage.cs rename to tests/Unit/WorkInProgress/FakeObjects/FakeMethodCallMessage.cs diff --git a/tests/HandlerInvocationFixture.cs b/tests/Unit/WorkInProgress/HandlerInvocationFixture.cs similarity index 100% rename from tests/HandlerInvocationFixture.cs rename to tests/Unit/WorkInProgress/HandlerInvocationFixture.cs diff --git a/tests/InterceptionConfigurationFixture.cs b/tests/Unit/WorkInProgress/InterceptionConfigurationFixture.cs similarity index 99% rename from tests/InterceptionConfigurationFixture.cs rename to tests/Unit/WorkInProgress/InterceptionConfigurationFixture.cs index fc985af..7a6939a 100644 --- a/tests/InterceptionConfigurationFixture.cs +++ b/tests/Unit/WorkInProgress/InterceptionConfigurationFixture.cs @@ -7,6 +7,7 @@ using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception; using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception; using Unity.Interception.PolicyInjection; +using Unity.Interception.Tests; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests { diff --git a/tests/MatchingRules/AssemblyMatchingRuleFixture.cs b/tests/Unit/WorkInProgress/MatchingRules/AssemblyMatchingRuleFixture.cs similarity index 100% rename from tests/MatchingRules/AssemblyMatchingRuleFixture.cs rename to tests/Unit/WorkInProgress/MatchingRules/AssemblyMatchingRuleFixture.cs diff --git a/tests/MatchingRules/CustomAttributeMatchingRuleFixture.cs b/tests/Unit/WorkInProgress/MatchingRules/CustomAttributeMatchingRuleFixture.cs similarity index 100% rename from tests/MatchingRules/CustomAttributeMatchingRuleFixture.cs rename to tests/Unit/WorkInProgress/MatchingRules/CustomAttributeMatchingRuleFixture.cs diff --git a/tests/MatchingRules/GlobFixture.cs b/tests/Unit/WorkInProgress/MatchingRules/GlobFixture.cs similarity index 100% rename from tests/MatchingRules/GlobFixture.cs rename to tests/Unit/WorkInProgress/MatchingRules/GlobFixture.cs diff --git a/tests/MatchingRules/MemberNameMatchingRuleFixture.cs b/tests/Unit/WorkInProgress/MatchingRules/MemberNameMatchingRuleFixture.cs similarity index 100% rename from tests/MatchingRules/MemberNameMatchingRuleFixture.cs rename to tests/Unit/WorkInProgress/MatchingRules/MemberNameMatchingRuleFixture.cs diff --git a/tests/MatchingRules/MethodSignatureMatchingRuleFixture.cs b/tests/Unit/WorkInProgress/MatchingRules/MethodSignatureMatchingRuleFixture.cs similarity index 100% rename from tests/MatchingRules/MethodSignatureMatchingRuleFixture.cs rename to tests/Unit/WorkInProgress/MatchingRules/MethodSignatureMatchingRuleFixture.cs diff --git a/tests/MatchingRules/NamespaceMatchingRuleFixture.cs b/tests/Unit/WorkInProgress/MatchingRules/NamespaceMatchingRuleFixture.cs similarity index 94% rename from tests/MatchingRules/NamespaceMatchingRuleFixture.cs rename to tests/Unit/WorkInProgress/MatchingRules/NamespaceMatchingRuleFixture.cs index aafa3a1..704eb68 100644 --- a/tests/MatchingRules/NamespaceMatchingRuleFixture.cs +++ b/tests/Unit/WorkInProgress/MatchingRules/NamespaceMatchingRuleFixture.cs @@ -1,17 +1,13 @@ - - -using System; -using System.Diagnostics.CodeAnalysis; -using System.Reflection; -using Microsoft.Practices.Unity.InterceptionExtension.Tests.MatchingRules.SeparateTopLevel; +using Microsoft.Practices.Unity.InterceptionExtension.Tests.MatchingRules.SeparateTopLevel; using Microsoft.Practices.Unity.InterceptionExtension.Tests.MatchingRules.TopLevel; using Microsoft.Practices.Unity.InterceptionExtension.Tests.MatchingRules.TopLevel.SecondLevel; using Microsoft.Practices.Unity.InterceptionExtension.Tests.MatchingRules.TopLevel.SecondLevel.ThirdLevel; using Microsoft.Practices.Unity.InterceptionExtension.Tests.MatchingRules.TopLevelTwo; using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Reflection; using Unity.Interception.PolicyInjection.MatchingRules; -[module: SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1403:FileMayOnlyContainASingleNamespace", Justification = "Test needs multiple namespaces so keep the namespaces and test together")] namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.MatchingRules { diff --git a/tests/MatchingRules/ParameterTypeMatchingRuleFixture.cs b/tests/Unit/WorkInProgress/MatchingRules/ParameterTypeMatchingRuleFixture.cs similarity index 100% rename from tests/MatchingRules/ParameterTypeMatchingRuleFixture.cs rename to tests/Unit/WorkInProgress/MatchingRules/ParameterTypeMatchingRuleFixture.cs diff --git a/tests/MatchingRules/PropertyMatchingRuleFixture.cs b/tests/Unit/WorkInProgress/MatchingRules/PropertyMatchingRuleFixture.cs similarity index 100% rename from tests/MatchingRules/PropertyMatchingRuleFixture.cs rename to tests/Unit/WorkInProgress/MatchingRules/PropertyMatchingRuleFixture.cs diff --git a/tests/MatchingRules/ReturnTypeMatchingRuleFixture.cs b/tests/Unit/WorkInProgress/MatchingRules/ReturnTypeMatchingRuleFixture.cs similarity index 100% rename from tests/MatchingRules/ReturnTypeMatchingRuleFixture.cs rename to tests/Unit/WorkInProgress/MatchingRules/ReturnTypeMatchingRuleFixture.cs diff --git a/tests/MatchingRules/TagAttributeMatchingRuleFixture.cs b/tests/Unit/WorkInProgress/MatchingRules/TagAttributeMatchingRuleFixture.cs similarity index 100% rename from tests/MatchingRules/TagAttributeMatchingRuleFixture.cs rename to tests/Unit/WorkInProgress/MatchingRules/TagAttributeMatchingRuleFixture.cs diff --git a/tests/MatchingRules/TypeMatchingRuleFixture.cs b/tests/Unit/WorkInProgress/MatchingRules/TypeMatchingRuleFixture.cs similarity index 92% rename from tests/MatchingRules/TypeMatchingRuleFixture.cs rename to tests/Unit/WorkInProgress/MatchingRules/TypeMatchingRuleFixture.cs index 6b0cc81..bc61205 100644 --- a/tests/MatchingRules/TypeMatchingRuleFixture.cs +++ b/tests/Unit/WorkInProgress/MatchingRules/TypeMatchingRuleFixture.cs @@ -1,11 +1,8 @@ - +using Microsoft.VisualStudio.TestTools.UnitTesting; using System; -using System.Diagnostics.CodeAnalysis; using System.Reflection; -using Microsoft.VisualStudio.TestTools.UnitTesting; using Unity.Interception.PolicyInjection.MatchingRules; -[module: SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1403:FileMayOnlyContainASingleNamespace", Justification = "Test needs multiple namespaces so keep the namespaces and test together")] namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.MatchingRules { diff --git a/tests/MethodSignatureFixture.cs b/tests/Unit/WorkInProgress/MethodSignatureFixture.cs similarity index 100% rename from tests/MethodSignatureFixture.cs rename to tests/Unit/WorkInProgress/MethodSignatureFixture.cs diff --git a/tests/ObjectsUnderTest/ClassWithGenericMethod.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/ClassWithGenericMethod.cs similarity index 100% rename from tests/ObjectsUnderTest/ClassWithGenericMethod.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/ClassWithGenericMethod.cs diff --git a/tests/ObjectsUnderTest/CritialFakeDal.Desktop.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/CritialFakeDal.Desktop.cs similarity index 100% rename from tests/ObjectsUnderTest/CritialFakeDal.Desktop.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/CritialFakeDal.Desktop.cs diff --git a/tests/ObjectsUnderTest/CriticalFakeDal.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/CriticalFakeDal.cs similarity index 100% rename from tests/ObjectsUnderTest/CriticalFakeDal.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/CriticalFakeDal.cs diff --git a/tests/ObjectsUnderTest/ExceptionEatingHandler.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/ExceptionEatingHandler.cs similarity index 100% rename from tests/ObjectsUnderTest/ExceptionEatingHandler.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/ExceptionEatingHandler.cs diff --git a/tests/ObjectsUnderTest/ExceptionSwizzlerHandler.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/ExceptionSwizzlerHandler.cs similarity index 100% rename from tests/ObjectsUnderTest/ExceptionSwizzlerHandler.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/ExceptionSwizzlerHandler.cs diff --git a/tests/ObjectsUnderTest/IInterfaceWithGenericMethod.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/IInterfaceWithGenericMethod.cs similarity index 100% rename from tests/ObjectsUnderTest/IInterfaceWithGenericMethod.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/IInterfaceWithGenericMethod.cs diff --git a/tests/ObjectsUnderTest/InterfacesOnlyDal.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/InterfacesOnlyDal.cs similarity index 80% rename from tests/ObjectsUnderTest/InterfacesOnlyDal.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/InterfacesOnlyDal.cs index 5f9586c..2e383f1 100644 --- a/tests/ObjectsUnderTest/InterfacesOnlyDal.cs +++ b/tests/Unit/WorkInProgress/ObjectsUnderTest/InterfacesOnlyDal.cs @@ -1,8 +1,4 @@ - - -using System; -using System.Collections.Specialized; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using Unity.Interception.Tests; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.ObjectsUnderTest { diff --git a/tests/ObjectsUnderTest/MakeReturnNullHandler.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/MakeReturnNullHandler.cs similarity index 100% rename from tests/ObjectsUnderTest/MakeReturnNullHandler.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/MakeReturnNullHandler.cs diff --git a/tests/ObjectsUnderTest/MockDal.Desktop.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/MockDal.Desktop.cs similarity index 100% rename from tests/ObjectsUnderTest/MockDal.Desktop.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/MockDal.Desktop.cs diff --git a/tests/ObjectsUnderTest/MockDalWithOverloads.Desktop.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/MockDalWithOverloads.Desktop.cs similarity index 100% rename from tests/ObjectsUnderTest/MockDalWithOverloads.Desktop.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/MockDalWithOverloads.Desktop.cs diff --git a/tests/ObjectsUnderTest/MockDalWithOverloads.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/MockDalWithOverloads.cs similarity index 100% rename from tests/ObjectsUnderTest/MockDalWithOverloads.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/MockDalWithOverloads.cs diff --git a/tests/ObjectsUnderTest/PostCallCountHandler.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/PostCallCountHandler.cs similarity index 100% rename from tests/ObjectsUnderTest/PostCallCountHandler.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/PostCallCountHandler.cs diff --git a/tests/ObjectsUnderTest/ShortcuttingHandler.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/ShortcuttingHandler.cs similarity index 100% rename from tests/ObjectsUnderTest/ShortcuttingHandler.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/ShortcuttingHandler.cs diff --git a/tests/ObjectsUnderTest/TestHandler.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/TestHandler.cs similarity index 100% rename from tests/ObjectsUnderTest/TestHandler.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/TestHandler.cs diff --git a/tests/ObjectsUnderTest/TestHandlerAttribute.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/TestHandlerAttribute.cs similarity index 100% rename from tests/ObjectsUnderTest/TestHandlerAttribute.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/TestHandlerAttribute.cs diff --git a/tests/ObjectsUnderTest/TypeMatchingAssignmentRule.cs b/tests/Unit/WorkInProgress/ObjectsUnderTest/TypeMatchingAssignmentRule.cs similarity index 100% rename from tests/ObjectsUnderTest/TypeMatchingAssignmentRule.cs rename to tests/Unit/WorkInProgress/ObjectsUnderTest/TypeMatchingAssignmentRule.cs diff --git a/tests/ParameterCollectionFixture.cs b/tests/Unit/WorkInProgress/ParameterCollectionFixture.cs similarity index 85% rename from tests/ParameterCollectionFixture.cs rename to tests/Unit/WorkInProgress/ParameterCollectionFixture.cs index a4d35be..d5221e1 100644 --- a/tests/ParameterCollectionFixture.cs +++ b/tests/Unit/WorkInProgress/ParameterCollectionFixture.cs @@ -1,23 +1,26 @@ - - -using System.Linq; -using Microsoft.Practices.Unity.TestSupport; +using Microsoft.Practices.Unity.TestSupport; using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Linq; +using System.Reflection; using Unity.Interception.PolicyInjection.Pipeline; -using Unity.Interception.Utilities; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests { [TestClass] public class ParameterCollectionFixture { + private static readonly ParameterInfo[] TestMethodParameters = typeof(ParameterCollectionFixture) + .GetMethod(nameof(ParameterCollectionFixture.TestMethod)) + .GetParameters(); + + [TestMethod] public void CanAccessNonFilteredParameters() { var collection = new ParameterCollection( new object[] { 10, 20, 30, 40, 50 }, - StaticReflection.GetMethodInfo(() => TestMethod(null, null, null, null, null)).GetParameters(), + TestMethodParameters, pi => true); Assert.AreEqual(5, collection.Count); @@ -45,7 +48,7 @@ public void CanAccessFilteredParameters() var collection = new ParameterCollection( new object[] { 10, 20, 30, 40, 50 }, - StaticReflection.GetMethodInfo(() => TestMethod(null, null, null, null, null)).GetParameters(), + TestMethodParameters, pi => param++ % 2 == 1); Assert.AreEqual(3, collection.Count); @@ -69,11 +72,9 @@ public void CanAccessFilteredParameters() [TestMethod] public void FilteredCollectionReturnsRightParameterByName() { - object dummy; - object dummy2; var inputsCollection = new ParameterCollection(new object[] { "one", "two", "three", "four" }, - StaticReflection.GetMethodInfo(() => MethodWithOuts(out dummy, null, out dummy2, null)).GetParameters(), + typeof(ParameterCollectionFixture).GetMethod(nameof(ParameterCollectionFixture.MethodWithOuts)).GetParameters(), pi => !pi.IsOut); Assert.AreEqual(2, inputsCollection.Count); @@ -88,7 +89,7 @@ public void WhenParameterValueIsNull() var collection = new ParameterCollection( new object[] { null }, - StaticReflection.GetMethodInfo(() => TestMethod(null, null, null, null, null)).GetParameters(), + TestMethodParameters, p => true); var result = collection.Contains(null); @@ -102,13 +103,14 @@ public void ContainsParameterWorksAsExpected() var collection = new ParameterCollection( new object[] { null }, - StaticReflection.GetMethodInfo(() => TestMethod(null, null, null, null, null)).GetParameters(), + TestMethodParameters, p => true); Assert.IsTrue(new[] { "param1", "param2", "param3", "param4", "param5" }.All(collection.ContainsParameter)); Assert.IsTrue(new[] { "someOtherParam", "notThisOneEither" }.All(p => !collection.ContainsParameter(p))); } +#pragma warning disable IDE0060 // Remove unused parameter public static void TestMethod(object param1, object param2, object param3, object param4, object param5) { } @@ -118,5 +120,6 @@ public static void MethodWithOuts(out object param1, object param2, out object p param1 = null; param3 = null; } +#pragma warning restore IDE0060 // Remove unused parameter } } diff --git a/tests/PipelineFixture.cs b/tests/Unit/WorkInProgress/PipelineFixture.cs similarity index 99% rename from tests/PipelineFixture.cs rename to tests/Unit/WorkInProgress/PipelineFixture.cs index 98ac039..893e09e 100644 --- a/tests/PipelineFixture.cs +++ b/tests/Unit/WorkInProgress/PipelineFixture.cs @@ -2,7 +2,6 @@ using System.Reflection; using Microsoft.Practices.Unity.InterceptionExtension.Tests.ObjectsUnderTest; -using Microsoft.Practices.Unity.TestSupport; using Microsoft.VisualStudio.TestTools.UnitTesting; using Unity; using Unity.Interception.Interceptors; @@ -10,6 +9,7 @@ using Unity.Interception.PolicyInjection.MatchingRules; using Unity.Interception.PolicyInjection.Pipeline; using Unity.Interception.PolicyInjection.Policies; +using Unity.Interception.Tests; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests { diff --git a/tests/PolicyInjection/HandlerPipelineKeyFixture.cs b/tests/Unit/WorkInProgress/PolicyInjection/HandlerPipelineKeyFixture.cs similarity index 58% rename from tests/PolicyInjection/HandlerPipelineKeyFixture.cs rename to tests/Unit/WorkInProgress/PolicyInjection/HandlerPipelineKeyFixture.cs index 81e612f..5c40f03 100644 --- a/tests/PolicyInjection/HandlerPipelineKeyFixture.cs +++ b/tests/Unit/WorkInProgress/PolicyInjection/HandlerPipelineKeyFixture.cs @@ -1,19 +1,21 @@ - - -using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Reflection; using Unity.Interception.PolicyInjection; -using Unity.Interception.Utilities; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.PolicyInjection { [TestClass] public class HandlerPipelineKeyFixture { + private static readonly MethodInfo Method1 = typeof(Base).GetMethod(nameof(Base.Method1)); + private static readonly MethodInfo Method2 = typeof(Base).GetMethod(nameof(Base.Method2)); + private static readonly MethodInfo ToStringMethod = typeof(Base).GetMethod(nameof(Base.ToString)); + [TestMethod] public void KeysForSameMethodAreEqual() { - var key1 = HandlerPipelineKey.ForMethod(StaticReflection.GetMethodInfo(b => b.Method1())); - var key2 = HandlerPipelineKey.ForMethod(StaticReflection.GetMethodInfo(b => b.Method1())); + var key1 = HandlerPipelineKey.ForMethod(Method1); + var key2 = HandlerPipelineKey.ForMethod(Method1); Assert.AreEqual(key1, key2); } @@ -21,8 +23,8 @@ public void KeysForSameMethodAreEqual() [TestMethod] public void KeysForSameMethodReflectedFromDifferentTypesAreEqual() { - var key1 = HandlerPipelineKey.ForMethod(StaticReflection.GetMethodInfo(b => b.Method2())); - var key2 = HandlerPipelineKey.ForMethod(StaticReflection.GetMethodInfo(b => b.Method2())); + var key1 = HandlerPipelineKey.ForMethod(Method2); + var key2 = HandlerPipelineKey.ForMethod(Method2); Assert.AreEqual(key1, key2); } @@ -30,8 +32,8 @@ public void KeysForSameMethodReflectedFromDifferentTypesAreEqual() [TestMethod] public void KeysForSameMethodReflectedFromDifferentTypesOnDifferentModulesAreEqual() { - var key1 = HandlerPipelineKey.ForMethod(StaticReflection.GetMethodInfo(o => o.ToString())); - var key2 = HandlerPipelineKey.ForMethod(StaticReflection.GetMethodInfo(b => b.ToString())); + var key1 = HandlerPipelineKey.ForMethod(ToStringMethod); + var key2 = HandlerPipelineKey.ForMethod(ToStringMethod); Assert.AreEqual(key1, key2); } @@ -39,8 +41,8 @@ public void KeysForSameMethodReflectedFromDifferentTypesOnDifferentModulesAreEqu [TestMethod] public void KeysForDifferentMethodsAreNotEqual() { - var key1 = HandlerPipelineKey.ForMethod(StaticReflection.GetMethodInfo(b => b.Method1())); - var key2 = HandlerPipelineKey.ForMethod(StaticReflection.GetMethodInfo(b => b.Method2())); + var key1 = HandlerPipelineKey.ForMethod(Method1); + var key2 = HandlerPipelineKey.ForMethod(Method2); Assert.AreNotEqual(key1, key2); } @@ -49,8 +51,8 @@ public void KeysForDifferentMethodsAreNotEqual() public void KeysForOverridenMethodReflectedFromDifferentTypesAreNotEqual() { // using plain reflection - lambdas get optimized so we cannot get the override through them - var key1 = HandlerPipelineKey.ForMethod(typeof(Base).GetMethod("Method1")); - var key2 = HandlerPipelineKey.ForMethod(typeof(Derived).GetMethod("Method1")); + var key1 = HandlerPipelineKey.ForMethod(Method1); + var key2 = HandlerPipelineKey.ForMethod(typeof(Derived).GetMethod(nameof(Derived.Method1))); Assert.AreNotEqual(key1, key2); } diff --git a/tests/PolicyInjection/PolicyInjectionBehaviorFixture.cs b/tests/Unit/WorkInProgress/PolicyInjection/PolicyInjectionBehaviorFixture.cs similarity index 100% rename from tests/PolicyInjection/PolicyInjectionBehaviorFixture.cs rename to tests/Unit/WorkInProgress/PolicyInjection/PolicyInjectionBehaviorFixture.cs diff --git a/tests/PolicyInjection/PolicyInjectionWithGenericMethodsFixture.Desktop.cs b/tests/Unit/WorkInProgress/PolicyInjection/PolicyInjectionWithGenericMethodsFixture.Desktop.cs similarity index 100% rename from tests/PolicyInjection/PolicyInjectionWithGenericMethodsFixture.Desktop.cs rename to tests/Unit/WorkInProgress/PolicyInjection/PolicyInjectionWithGenericMethodsFixture.Desktop.cs diff --git a/tests/PolicyInjection/PolicyInjectionWithGenericMethodsFixture.cs b/tests/Unit/WorkInProgress/PolicyInjection/PolicyInjectionWithGenericMethodsFixture.cs similarity index 99% rename from tests/PolicyInjection/PolicyInjectionWithGenericMethodsFixture.cs rename to tests/Unit/WorkInProgress/PolicyInjection/PolicyInjectionWithGenericMethodsFixture.cs index bbe5e79..3f14f0b 100644 --- a/tests/PolicyInjection/PolicyInjectionWithGenericMethodsFixture.cs +++ b/tests/Unit/WorkInProgress/PolicyInjection/PolicyInjectionWithGenericMethodsFixture.cs @@ -7,6 +7,7 @@ using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception; using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception; using Unity.Interception.PolicyInjection; +using Unity.Interception.Tests; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.PolicyInjection { diff --git a/tests/PolicyInjection/VirtualMethodOverrideFixture.Desktop.cs b/tests/Unit/WorkInProgress/PolicyInjection/VirtualMethodOverrideFixture.Desktop.cs similarity index 100% rename from tests/PolicyInjection/VirtualMethodOverrideFixture.Desktop.cs rename to tests/Unit/WorkInProgress/PolicyInjection/VirtualMethodOverrideFixture.Desktop.cs diff --git a/tests/PolicyInjection/VirtualMethodOverrideFixture.cs b/tests/Unit/WorkInProgress/PolicyInjection/VirtualMethodOverrideFixture.cs similarity index 100% rename from tests/PolicyInjection/VirtualMethodOverrideFixture.cs rename to tests/Unit/WorkInProgress/PolicyInjection/VirtualMethodOverrideFixture.cs diff --git a/tests/PolicySetFixture.cs b/tests/Unit/WorkInProgress/PolicySetFixture.cs similarity index 86% rename from tests/PolicySetFixture.cs rename to tests/Unit/WorkInProgress/PolicySetFixture.cs index 513f592..153edbb 100644 --- a/tests/PolicySetFixture.cs +++ b/tests/Unit/WorkInProgress/PolicySetFixture.cs @@ -1,15 +1,16 @@  using System; +using System.Collections; using System.Collections.Generic; using System.Reflection; -using Microsoft.Practices.Unity.TestSupport; using Microsoft.VisualStudio.TestTools.UnitTesting; using Unity; using Unity.Interception.Interceptors; using Unity.Interception.PolicyInjection.MatchingRules; using Unity.Interception.PolicyInjection.Pipeline; using Unity.Interception.PolicyInjection.Policies; +using Unity.Interception.Tests; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests { @@ -281,6 +282,93 @@ private MethodImplementationInfo GetMethodImplInfo(string methodName) } } + + + #region Test Data + + public class Handler1 : ICallHandler + { + private int order = 0; + + /// + /// Gets or sets the order in which the handler will be executed + /// + public int Order + { + get { return order; } + set { order = value; } + } + + public IMethodReturn Invoke(IMethodInvocation input, + GetNextHandlerDelegate getNext) + { + throw new NotImplementedException(); + } + } + + public class Handler2 : ICallHandler + { + private int order = 0; + + /// + /// Gets or sets the order in which the handler will be executed + /// + public int Order + { + get { return order; } + set { order = value; } + } + + public IMethodReturn Invoke(IMethodInvocation input, + GetNextHandlerDelegate getNext) + { + throw new NotImplementedException(); + } + } + + public class Handler3 : ICallHandler + { + private int order = 0; + + /// + /// Gets or sets the order in which the handler will be executed + /// + public int Order + { + get { return order; } + set { order = value; } + } + + public IMethodReturn Invoke(IMethodInvocation input, + GetNextHandlerDelegate getNext) + { + throw new NotImplementedException(); + } + } + + public interface IYetAnotherInterface + { + void MyMethod(); + } + + public class YetAnotherMyType : IYetAnotherInterface + { + public void MyMethod() { } + } + + public class TypeComparer : IComparer + { + public int Compare(object x, object y) + { + if (x.GetType() == y.GetType()) + { + return 0; + } + return -1; + } + } + + internal class MatchesByType { // Matches type policy @@ -381,4 +469,6 @@ public override ICallHandler CreateHandler(IUnityContainer ignored) return new MarkerCallHandler(this.handlerName); } } + + #endregion } diff --git a/tests/TestSupport/AssertExtensions.cs b/tests/Unit/WorkInProgress/TestSupport/AssertExtensions.cs similarity index 100% rename from tests/TestSupport/AssertExtensions.cs rename to tests/Unit/WorkInProgress/TestSupport/AssertExtensions.cs diff --git a/tests/TestSupport/CollectionAssertExtensions.cs b/tests/Unit/WorkInProgress/TestSupport/CollectionAssertExtensions.cs similarity index 100% rename from tests/TestSupport/CollectionAssertExtensions.cs rename to tests/Unit/WorkInProgress/TestSupport/CollectionAssertExtensions.cs diff --git a/tests/TestSupport/EnumerableAssertionExtensions.cs b/tests/Unit/WorkInProgress/TestSupport/EnumerableAssertionExtensions.cs similarity index 100% rename from tests/TestSupport/EnumerableAssertionExtensions.cs rename to tests/Unit/WorkInProgress/TestSupport/EnumerableAssertionExtensions.cs diff --git a/tests/TestSupport/ExtensibilityTestExtension.cs b/tests/Unit/WorkInProgress/TestSupport/ExtensibilityTestExtension.cs similarity index 100% rename from tests/TestSupport/ExtensibilityTestExtension.cs rename to tests/Unit/WorkInProgress/TestSupport/ExtensibilityTestExtension.cs diff --git a/tests/TestSupport/GlobalCountInterceptionBehavior.cs b/tests/Unit/WorkInProgress/TestSupport/GlobalCountInterceptionBehavior.cs similarity index 100% rename from tests/TestSupport/GlobalCountInterceptionBehavior.cs rename to tests/Unit/WorkInProgress/TestSupport/GlobalCountInterceptionBehavior.cs diff --git a/tests/TestSupport/ILogger.cs b/tests/Unit/WorkInProgress/TestSupport/ILogger.cs similarity index 100% rename from tests/TestSupport/ILogger.cs rename to tests/Unit/WorkInProgress/TestSupport/ILogger.cs diff --git a/tests/TestSupport/MockContainerExtension.cs b/tests/Unit/WorkInProgress/TestSupport/MockContainerExtension.cs similarity index 93% rename from tests/TestSupport/MockContainerExtension.cs rename to tests/Unit/WorkInProgress/TestSupport/MockContainerExtension.cs index cc18a24..fec840e 100644 --- a/tests/TestSupport/MockContainerExtension.cs +++ b/tests/Unit/WorkInProgress/TestSupport/MockContainerExtension.cs @@ -13,7 +13,7 @@ public bool InitializeWasCalled get { return this.initializeWasCalled; } } - public new ExtensionContext Context + public new IExtensionContext Context { get { return base.Context; } } diff --git a/tests/TestSupport/MockDatabase.cs b/tests/Unit/WorkInProgress/TestSupport/MockDatabase.cs similarity index 100% rename from tests/TestSupport/MockDatabase.cs rename to tests/Unit/WorkInProgress/TestSupport/MockDatabase.cs diff --git a/tests/TestSupport/MockLogger.cs b/tests/Unit/WorkInProgress/TestSupport/MockLogger.cs similarity index 100% rename from tests/TestSupport/MockLogger.cs rename to tests/Unit/WorkInProgress/TestSupport/MockLogger.cs diff --git a/tests/TestSupport/NegativeTypeConverter.cs b/tests/Unit/WorkInProgress/TestSupport/NegativeTypeConverter.cs similarity index 100% rename from tests/TestSupport/NegativeTypeConverter.cs rename to tests/Unit/WorkInProgress/TestSupport/NegativeTypeConverter.cs diff --git a/tests/TestSupport/ObjectUsingLogger.cs b/tests/Unit/WorkInProgress/TestSupport/ObjectUsingLogger.cs similarity index 100% rename from tests/TestSupport/ObjectUsingLogger.cs rename to tests/Unit/WorkInProgress/TestSupport/ObjectUsingLogger.cs diff --git a/tests/TestSupport/ObjectWithInjectionMethod.cs b/tests/Unit/WorkInProgress/TestSupport/ObjectWithInjectionMethod.cs similarity index 100% rename from tests/TestSupport/ObjectWithInjectionMethod.cs rename to tests/Unit/WorkInProgress/TestSupport/ObjectWithInjectionMethod.cs diff --git a/tests/TestSupport/ObjectWithOneConstructorDependency.cs b/tests/Unit/WorkInProgress/TestSupport/ObjectWithOneConstructorDependency.cs similarity index 100% rename from tests/TestSupport/ObjectWithOneConstructorDependency.cs rename to tests/Unit/WorkInProgress/TestSupport/ObjectWithOneConstructorDependency.cs diff --git a/tests/TestSupport/ObjectWithTwoConstructorParameters.cs b/tests/Unit/WorkInProgress/TestSupport/ObjectWithTwoConstructorParameters.cs similarity index 100% rename from tests/TestSupport/ObjectWithTwoConstructorParameters.cs rename to tests/Unit/WorkInProgress/TestSupport/ObjectWithTwoConstructorParameters.cs diff --git a/tests/TestSupport/ObjectWithTwoProperties.cs b/tests/Unit/WorkInProgress/TestSupport/ObjectWithTwoProperties.cs similarity index 100% rename from tests/TestSupport/ObjectWithTwoProperties.cs rename to tests/Unit/WorkInProgress/TestSupport/ObjectWithTwoProperties.cs diff --git a/tests/TestSupport/SessionLifetimeManager.cs b/tests/Unit/WorkInProgress/TestSupport/SessionLifetimeManager.cs similarity index 100% rename from tests/TestSupport/SessionLifetimeManager.cs rename to tests/Unit/WorkInProgress/TestSupport/SessionLifetimeManager.cs diff --git a/tests/TestSupport/SpecialLogger.cs b/tests/Unit/WorkInProgress/TestSupport/SpecialLogger.cs similarity index 100% rename from tests/TestSupport/SpecialLogger.cs rename to tests/Unit/WorkInProgress/TestSupport/SpecialLogger.cs diff --git a/tests/TestSupport/TypeReflectionExtensions.cs b/tests/Unit/WorkInProgress/TestSupport/TypeReflectionExtensions.cs similarity index 100% rename from tests/TestSupport/TypeReflectionExtensions.cs rename to tests/Unit/WorkInProgress/TestSupport/TypeReflectionExtensions.cs diff --git a/tests/TransparentProxyInterception/IntegrationFixture.cs b/tests/Unit/WorkInProgress/TransparentProxyInterception/IntegrationFixture.cs similarity index 100% rename from tests/TransparentProxyInterception/IntegrationFixture.cs rename to tests/Unit/WorkInProgress/TransparentProxyInterception/IntegrationFixture.cs diff --git a/tests/TransparentProxyInterception/TransparentProxyInterceptorFixture.cs b/tests/Unit/WorkInProgress/TransparentProxyInterception/TransparentProxyInterceptorFixture.cs similarity index 100% rename from tests/TransparentProxyInterception/TransparentProxyInterceptorFixture.cs rename to tests/Unit/WorkInProgress/TransparentProxyInterception/TransparentProxyInterceptorFixture.cs diff --git a/tests/TransparentProxyInterception/TransparentProxyMethodInvocationFixture.cs b/tests/Unit/WorkInProgress/TransparentProxyInterception/TransparentProxyMethodInvocationFixture.cs similarity index 100% rename from tests/TransparentProxyInterception/TransparentProxyMethodInvocationFixture.cs rename to tests/Unit/WorkInProgress/TransparentProxyInterception/TransparentProxyMethodInvocationFixture.cs diff --git a/tests/VirtualMethodInterception/InterceptingClassGenerationFixture.Desktop.cs b/tests/Unit/WorkInProgress/VirtualMethodInterception/InterceptingClassGenerationFixture.Desktop.cs similarity index 100% rename from tests/VirtualMethodInterception/InterceptingClassGenerationFixture.Desktop.cs rename to tests/Unit/WorkInProgress/VirtualMethodInterception/InterceptingClassGenerationFixture.Desktop.cs diff --git a/tests/VirtualMethodInterception/InterceptingClassGenerationFixture.cs b/tests/Unit/WorkInProgress/VirtualMethodInterception/InterceptingClassGenerationFixture.cs similarity index 80% rename from tests/VirtualMethodInterception/InterceptingClassGenerationFixture.cs rename to tests/Unit/WorkInProgress/VirtualMethodInterception/InterceptingClassGenerationFixture.cs index 3fcb471..4848e93 100644 --- a/tests/VirtualMethodInterception/InterceptingClassGenerationFixture.cs +++ b/tests/Unit/WorkInProgress/VirtualMethodInterception/InterceptingClassGenerationFixture.cs @@ -1,20 +1,20 @@ - - +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.ComponentModel; using System.Linq; using System.Reflection; using System.Security.Permissions; -using Microsoft.Practices.Unity.InterceptionExtension.Tests.ObjectsUnderTest; -using Microsoft.Practices.Unity.TestSupport; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Text; using Unity.Interception.InterceptionBehaviors; using Unity.Interception.Interceptors; using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception; +using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration; using Unity.Interception.PolicyInjection; using Unity.Interception.PolicyInjection.Pipeline; -using Unity.Interception.Utilities; +using Unity.Interception.Tests; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.VirtualMethodInterception { @@ -70,8 +70,8 @@ public void CanInterceptVoidNoArgMethods() public void InterceptingClassOverridesBaseClassVirtualMethods() { Type baseType = typeof(ClassWithDefaultCtor); - VirtualMethodInterceptor interceptor = new VirtualMethodInterceptor(); - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(baseType); + _ = new VirtualMethodInterceptor(); + InterceptingClassGenerator generator = new InterceptingClassGenerator(baseType); Type generatedType = generator.GenerateType(); MethodInfo methodOne = generatedType.GetMethod("MethodOne"); @@ -203,10 +203,8 @@ public void CanInterceptMethodsWithOutParameters() PostCallCountHandler handler = new PostCallCountHandler(); ClassWithDefaultCtor instance = WireupHelper.GetInterceptedInstance("OutParams", handler); - int plusOne; - int timesTwo; - instance.OutParams(5, out plusOne, out timesTwo); + instance.OutParams(5, out int plusOne, out int timesTwo); Assert.AreEqual(5 + 1, plusOne); Assert.AreEqual(5 * 2, timesTwo); @@ -253,7 +251,7 @@ public void FiringAnEventIsNotIntercepted() [TestMethod] public void AttemptingToInterceptInvalidClassThrows() { - PostCallCountHandler handler = new PostCallCountHandler(); + _ = new PostCallCountHandler(); VirtualMethodInterceptor interceptor = new VirtualMethodInterceptor(); try { @@ -303,7 +301,7 @@ public void GenericWrapperWorks() PipelineManager pm = new PipelineManager(); MethodBase reverse = typeof(InterceptingGenericClass).GetMethod("Reverse"); - pm.SetPipeline(reverse, new HandlerPipeline(Sequence.Collect(handler))); + pm.SetPipeline(reverse, new HandlerPipeline(new ICallHandler[] { handler })); ((IInterceptingProxy)instance).AddInterceptionBehavior(new PolicyInjectionBehavior(pm)); string result = instance.Reverse(137); @@ -342,8 +340,8 @@ public virtual void Something() public void CanImplementAdditionalInterfaces() { // arrange - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = - new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(MainType), typeof(IAdditionalInterface)); + InterceptingClassGenerator generator = + new InterceptingClassGenerator(typeof(MainType), typeof(IAdditionalInterface)); Type generatedType = generator.GenerateType(); // act @@ -358,7 +356,7 @@ public void CanImplementAdditionalInterfaces() public void InvokingMethodOnAdditionalInterfaceThrowsIfNotHandledByInterceptor() { // arrange - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(MainType), typeof(IAdditionalInterface)); + InterceptingClassGenerator generator = new InterceptingClassGenerator(typeof(MainType), typeof(IAdditionalInterface)); Type generatedType = generator.GenerateType(); object instance = Activator.CreateInstance(generatedType); @@ -382,7 +380,7 @@ public void InvokingMethodOnAdditionalInterfaceThrowsIfNotHandledByInterceptor() public void CanSuccessfullyInvokeAnAdditionalInterfaceMethodIfAnInterceptorDoesNotForwardTheCall() { // arrange - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(MainType), typeof(IAdditionalInterface)); + InterceptingClassGenerator generator = new InterceptingClassGenerator(typeof(MainType), typeof(IAdditionalInterface)); Type generatedType = generator.GenerateType(); object instance = Activator.CreateInstance(generatedType); bool invoked = false; @@ -401,11 +399,11 @@ public void CanSuccessfullyInvokeAnAdditionalInterfaceMethodIfAnInterceptorDoesN [TestMethod] public void CanImplementINotifyPropertyChanged() { - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(MainType), typeof(INotifyPropertyChanged)); + InterceptingClassGenerator generator = new InterceptingClassGenerator(typeof(MainType), typeof(INotifyPropertyChanged)); Type generatedType = generator.GenerateType(); object instance = Activator.CreateInstance(generatedType); string changeProperty = null; - PropertyChangedEventHandler handler = (sender, args) => changeProperty = args.PropertyName; + void handler(object sender, PropertyChangedEventArgs args) => changeProperty = args.PropertyName; ((IInterceptingProxy)instance).AddInterceptionBehavior(new NaiveINotifyPropertyChangedInterceptionBehavior()); ((INotifyPropertyChanged)instance).PropertyChanged += handler; @@ -428,8 +426,8 @@ public void CanImplementINotifyPropertyChanged() public void CanImplementAdditionalInterfaceWithMethodsHavingSignaturesMatchingMethodsInTheBaseClass() { // arrange - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = - new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(MainType), typeof(IDoSomething)); + InterceptingClassGenerator generator = + new InterceptingClassGenerator(typeof(MainType), typeof(IDoSomething)); Type generatedType = generator.GenerateType(); // act @@ -443,8 +441,8 @@ public void CanImplementAdditionalInterfaceWithMethodsHavingSignaturesMatchingMe [TestMethod] public void CanInvokeMethodsFromDifferentTypesWithMatchingSignatures() { - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = - new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(MainType), typeof(IDoSomething), typeof(IDoSomethingToo)); + InterceptingClassGenerator generator = + new InterceptingClassGenerator(typeof(MainType), typeof(IDoSomething), typeof(IDoSomethingToo)); Type generatedType = generator.GenerateType(); object instance = Activator.CreateInstance(generatedType); @@ -461,16 +459,16 @@ public void CanInvokeMethodsFromDifferentTypesWithMatchingSignatures() ((IDoSomething)instance).DoSomething(); ((IDoSomethingToo)instance).DoSomething(); - Assert.AreSame(StaticReflection.GetMethodInfo(i => i.DoSomething()), invokedMethods[0]); - Assert.AreSame(StaticReflection.GetMethodInfo(i => i.DoSomething()), invokedMethods[1]); - Assert.AreSame(StaticReflection.GetMethodInfo(i => i.DoSomething()), invokedMethods[2]); + Assert.AreSame(typeof(MainType).GetMethod(nameof(MainType.DoSomething)), invokedMethods[0]); + Assert.AreSame(typeof(IDoSomething).GetMethod(nameof(IDoSomething.DoSomething), new Type[0]), invokedMethods[1]); + Assert.AreSame(typeof(IDoSomethingToo).GetMethod(nameof(IDoSomethingToo.DoSomething)), invokedMethods[2]); } [TestMethod] public void DoesNotReImplementAdditionalInterfaceAlreadyImplementedByInterceptedClass() { - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = - new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(InterfaceImplementingMainType), typeof(IDeriveFromIDoSomething)); + InterceptingClassGenerator generator = + new InterceptingClassGenerator(typeof(InterfaceImplementingMainType), typeof(IDeriveFromIDoSomething)); Type generatedType = generator.GenerateType(); object instance = Activator.CreateInstance(generatedType); @@ -491,26 +489,20 @@ public void DoesNotReImplementAdditionalInterfaceAlreadyImplementedByIntercepted ((IDeriveFromIDoSomething)instance).DoSomething(String.Empty); ((IDeriveFromIDoSomething)instance).DoSomethingElse(); + var info = typeof(InterfaceImplementingMainType).GetMethod(nameof(InterfaceImplementingMainType.DoSomething), new Type[] { typeof(string) }); + Assert.AreEqual(4, interceptedMethods.Count); // only the virtual implicit method implementation is invoked for IDoSomething - Assert.AreSame( - StaticReflection.GetMethodInfo(i => i.DoSomething(null)), - interceptedMethods[0]); - Assert.AreSame( - StaticReflection.GetMethodInfo(i => i.DoSomething(null)), - interceptedMethods[1]); - Assert.AreSame( - StaticReflection.GetMethodInfo(i => i.DoSomething(null)), - interceptedMethods[2]); - Assert.AreSame( - StaticReflection.GetMethodInfo(i => i.DoSomethingElse()), - interceptedMethods[3]); + Assert.AreSame(info, interceptedMethods[0]); + Assert.AreSame(info, interceptedMethods[1]); + Assert.AreSame(info, interceptedMethods[2]); + Assert.AreSame(typeof(IDeriveFromIDoSomething).GetMethod(nameof(IDeriveFromIDoSomething.DoSomethingElse)), interceptedMethods[3]); } [TestMethod] public void CanInterceptProtectedVirtualProperties() { - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(ClassWithProtectedProperty)); + InterceptingClassGenerator generator = new InterceptingClassGenerator(typeof(ClassWithProtectedProperty)); Type generatedType = generator.GenerateType(); ClassWithProtectedProperty instance = (ClassWithProtectedProperty)Activator.CreateInstance(generatedType); @@ -533,8 +525,8 @@ public void CanInterceptProtectedVirtualProperties() [TestMethod] public void CanInterceptProtectedInternalVirtualProperties() { - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = - new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(ClassWithProtectedInternalProperty)); + InterceptingClassGenerator generator = + new InterceptingClassGenerator(typeof(ClassWithProtectedInternalProperty)); Type generatedType = generator.GenerateType(); ClassWithProtectedInternalProperty instance = @@ -558,7 +550,7 @@ public void CanInterceptProtectedInternalVirtualProperties() [TestMethod] public void DoesNotInterceptInternalVirtualProperties() { - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(ClassWithInternalProperty)); + InterceptingClassGenerator generator = new InterceptingClassGenerator(typeof(ClassWithInternalProperty)); Type generatedType = generator.GenerateType(); ClassWithInternalProperty instance = (ClassWithInternalProperty)Activator.CreateInstance(generatedType); @@ -581,8 +573,8 @@ public void DoesNotInterceptInternalVirtualProperties() [TestMethod] public void CanInterceptProtectedAccesorOnMixedPrivateProtectedVirtualProperties() { - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = - new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(ClassWithMixedPrivateProtectedProperty)); + InterceptingClassGenerator generator = + new InterceptingClassGenerator(typeof(ClassWithMixedPrivateProtectedProperty)); Type generatedType = generator.GenerateType(); ClassWithMixedPrivateProtectedProperty instance = @@ -606,8 +598,8 @@ public void CanInterceptProtectedAccesorOnMixedPrivateProtectedVirtualProperties [TestMethod] public void CanInterceptMixedPublicProtectedVirtualProperties() { - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = - new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(ClassWithMixedPublicProtectedProperty)); + InterceptingClassGenerator generator = + new InterceptingClassGenerator(typeof(ClassWithMixedPublicProtectedProperty)); Type generatedType = generator.GenerateType(); ClassWithMixedPublicProtectedProperty instance = @@ -631,8 +623,8 @@ public void CanInterceptMixedPublicProtectedVirtualProperties() [TestMethod] public void CanInterceptClassWithReservedTypeAttributes() { - global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = - new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeof(ClassWithPermissionAttribute)); + InterceptingClassGenerator generator = + new InterceptingClassGenerator(typeof(ClassWithPermissionAttribute)); Type generatedType = generator.GenerateType(); ClassWithPermissionAttribute instance = (ClassWithPermissionAttribute)Activator.CreateInstance(generatedType); @@ -684,7 +676,7 @@ public virtual string AddUp(int x, int y) public virtual int MethodWithRefParameters(int x, ref string y, float f) { - y = y + " hooray!"; + y += " hooray!"; return x + (int)f; } @@ -706,12 +698,6 @@ public class Wrapper : ClassWithDefaultCtor, IInterceptingProxy { private readonly InterceptionBehaviorPipeline pipeline = new InterceptionBehaviorPipeline(); - private static readonly MethodBase MethodOneMethod = typeof(ClassWithDefaultCtor).GetMethod("MethodOne"); - private static readonly MethodBase CalculateAnswerMethod = typeof(ClassWithDefaultCtor).GetMethod("CalculateAnswer"); - private static readonly MethodBase AddUpMethod = typeof(ClassWithDefaultCtor).GetMethod("AddUp"); - private static readonly MethodBase MethodWithRefParametersMethod = typeof(ClassWithDefaultCtor).GetMethod("MethodWithRefParameters"); - private static readonly MethodBase OutParamsMethod = typeof(ClassWithDefaultCtor).GetMethod("OutParams"); - private static readonly MethodBase MethodWithGenericReturnTypeMethod = typeof(ClassWithDefaultCtor).GetMethods() .Where(m => m.Name == "MethodWithGenericReturnType").First(); @@ -798,16 +784,28 @@ public virtual string Reverse(TItem obj) { char[] chars = obj.ToString().ToCharArray(); Array.Reverse(chars); - return chars.JoinStrings(String.Empty); + + var sb = new StringBuilder(); + chars.Aggregate(sb, (builder, item) => + { + if (builder.Length > 0) + { + builder.Append(String.Empty); + } + + builder.Append(item); + return builder; + }); + + return sb.ToString(); } } public class WrapperGeneric : InterceptingGenericClass, IInterceptingProxy { - private InterceptionBehaviorPipeline pipeline = new InterceptionBehaviorPipeline(); - private MethodBase reverse = typeof(InterceptingGenericClass).GetMethod("Reverse"); + private readonly InterceptionBehaviorPipeline pipeline = new InterceptionBehaviorPipeline(); + private readonly MethodBase reverse = typeof(InterceptingGenericClass).GetMethod("Reverse"); - [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1100:DoNotPrefixCallsWithBaseUnlessLocalImplementationExists", Justification = "Point of the test is to call base class and Reverse is overridden and virtual.")] private string BaseReverse(TITem obj) { return base.Reverse(obj); diff --git a/tests/VirtualMethodInterception/InterceptingInterfaceMethodsFixture.cs b/tests/Unit/WorkInProgress/VirtualMethodInterception/InterceptingInterfaceMethodsFixture.cs similarity index 89% rename from tests/VirtualMethodInterception/InterceptingInterfaceMethodsFixture.cs rename to tests/Unit/WorkInProgress/VirtualMethodInterception/InterceptingInterfaceMethodsFixture.cs index 53e6561..ae9e989 100644 --- a/tests/VirtualMethodInterception/InterceptingInterfaceMethodsFixture.cs +++ b/tests/Unit/WorkInProgress/VirtualMethodInterception/InterceptingInterfaceMethodsFixture.cs @@ -1,7 +1,5 @@ - - -using Microsoft.Practices.Unity.TestSupport; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Unity.Interception.Tests; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.VirtualMethodInterception { diff --git a/tests/VirtualMethodInterception/VirtualMethodInterceptorFixture.Desktop.cs b/tests/Unit/WorkInProgress/VirtualMethodInterception/VirtualMethodInterceptorFixture.Desktop.cs similarity index 100% rename from tests/VirtualMethodInterception/VirtualMethodInterceptorFixture.Desktop.cs rename to tests/Unit/WorkInProgress/VirtualMethodInterception/VirtualMethodInterceptorFixture.Desktop.cs diff --git a/tests/VirtualMethodInterception/VirtualMethodInterceptorFixture.cs b/tests/Unit/WorkInProgress/VirtualMethodInterception/VirtualMethodInterceptorFixture.cs similarity index 99% rename from tests/VirtualMethodInterception/VirtualMethodInterceptorFixture.cs rename to tests/Unit/WorkInProgress/VirtualMethodInterception/VirtualMethodInterceptorFixture.cs index 98e6c08..0defeda 100644 --- a/tests/VirtualMethodInterception/VirtualMethodInterceptorFixture.cs +++ b/tests/Unit/WorkInProgress/VirtualMethodInterception/VirtualMethodInterceptorFixture.cs @@ -12,6 +12,7 @@ using Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception; using Unity.Interception.PolicyInjection; using Unity.Interception.PolicyInjection.Pipeline; +using Unity.Interception.Tests; using Unity.Lifetime; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.VirtualMethodInterceptorTests diff --git a/tests/VirtualMethodInterception/WireupHelper.cs b/tests/Unit/WorkInProgress/VirtualMethodInterception/WireupHelper.cs similarity index 92% rename from tests/VirtualMethodInterception/WireupHelper.cs rename to tests/Unit/WorkInProgress/VirtualMethodInterception/WireupHelper.cs index 49b3183..5465ab3 100644 --- a/tests/VirtualMethodInterception/WireupHelper.cs +++ b/tests/Unit/WorkInProgress/VirtualMethodInterception/WireupHelper.cs @@ -1,11 +1,8 @@ - - -using System; +using System; using System.Reflection; using Unity.Interception.Interceptors; using Unity.Interception.PolicyInjection; using Unity.Interception.PolicyInjection.Pipeline; -using Unity.Interception.Utilities; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.VirtualMethodInterception { @@ -37,7 +34,7 @@ internal static T GetInterceptedInstance(string methodName, ICallHandler hand T instance = GetInterceptingInstance(); PipelineManager manager = new PipelineManager(); - manager.SetPipeline(method, new HandlerPipeline(Sequence.Collect(handler))); + manager.SetPipeline(method, new HandlerPipeline(new ICallHandler[] { handler })); IInterceptingProxy pm = (IInterceptingProxy)instance; pm.AddInterceptionBehavior(new PolicyInjectionBehavior(manager)); diff --git a/tests/Unity.Interception.Tests.csproj b/tests/Unity.Interception.Tests.csproj deleted file mode 100644 index 2ef4960..0000000 --- a/tests/Unity.Interception.Tests.csproj +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - net47 - false - Unity.Interception.Tests - - - - - - - - - - - - - - - ..\..\Abstractions\src\Unity.Abstractions.csproj - ..\..\Container\src\Unity.Container.csproj - - - - - - - - - - - - - - - - - - -