/// <summary>
        /// Sets the configuration.
        /// </summary>
        /// <param name="config">The config.</param>
        public override void SetConfiguration(AspectConfiguration config)
        {
            Proxy.Configuration = config;
            _kernel.Bind <IMasterProxy>().ToConstant(Proxy);

            config.Container = this;
        }
Exemple #2
0
        public void TestBasicBeforeAdvice()
        {
            var adviceMock = new Mock <IBeforeAdvice>();

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            string value = "";

            weaver.Advice(() => { value = "called"; });
            Assert.AreEqual("called", value);

            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);

            weaver.Advice("called2", arg => { value = arg; });
            Assert.AreEqual("called2", value);

            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <string, ValueTuple> >()), Times.Once);

            weaver.Advice(() => { value = "called3"; });
            Assert.AreEqual("called3", value);

            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Exactly(2));
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <string, ValueTuple> >()), Times.Once);
        }
Exemple #3
0
        public DefaultNonAspectTest()
        {
            var c = new AspectConfiguration();

            defaultTypePredicate   = c.NonPredicates.BuildNonAspectTypePredicate();
            defaultMethodPredicate = c.NonPredicates.BuildNonAspectMethodPredicate();
        }
        /// <summary>
        /// Sets the configuration.
        /// </summary>
        /// <param name="config">The config.</param>
        public override void SetConfiguration(AspectConfiguration config)
        {
            Proxy.Configuration = config;
            _kernel.Bind<IMasterProxy>().ToConstant(Proxy);

            config.Container = this;
        }
Exemple #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PluginsServiceProvider"/> class.
 /// </summary>
 /// <param name="services">The services.</param>
 /// <param name="pluginManagers"></param>
 /// <param name="pluginServiceTypeCache"></param>
 public PluginsServiceProvider(IServiceCollection services, IPluginManagers pluginManagers, PluginSerivceTypeCache pluginServiceTypeCache)
 {
     this._services              = services;
     this.pluginManagers         = pluginManagers;
     this.pluginServiceTypeCache = pluginServiceTypeCache;
     aspectConfiguration         = new AspectConfiguration();
 }
Exemple #6
0
        public void TestBeforeAdviceChangeParam()
        {
            var adviceMock = new Mock <IBeforeAdvice>();

            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()))
            .Callback(() => throw new InvalidOperationException());
            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <string, ValueTuple> >()))
            .Callback((Invocation <string, ValueTuple> invoc) => invoc.Parameter = "Changed");
            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <string, string> >()))
            .Callback((Invocation <string, string> invoc) => invoc.Parameter = "Changed 2");

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            weaver.Advice("Not Changed", arg => Assert.AreEqual("Changed", arg));
            Assert.AreEqual("Return", weaver.Advice("Not Changed", arg => {
                Assert.AreEqual("Changed 2", arg);
                return("Return");
            }));

            config = new AspectConfiguration();
            weaver = new AspectWeaver(config, this);

            weaver.Advice("Not Changed", arg => Assert.AreEqual("Not Changed", arg));
            Assert.AreEqual("Return", weaver.Advice("Not Changed", arg => {
                Assert.AreEqual("Not Changed", arg);
                return("Return");
            }));
        }
Exemple #7
0
        protected override void SetAspectConfiguration(AspectConfiguration aspectConfiguration, System.Reflection.MethodBase targetMethod)
        {
            LogAspectConfiguration configuration = (LogAspectConfiguration)aspectConfiguration;

            configuration.OnEntryOptions     = this.onEntryOptions;
            configuration.OnSuccessOptions   = this.onSuccessOptions;
            configuration.OnExceptionOptions = this.onExceptionOptions;
        }
Exemple #8
0
        /// <summary>
        /// Determines whether the specified target object has methods decorated for interception.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="configuration">The configuration.</param>
        /// <returns>
        /// 	<c>true</c> if the specified target is decorated; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsDecorated(this object target, AspectConfiguration configuration)
        {
            var methods = target.GetType().Methods();

            var isDecorated = methods.Any(m => m.Attributes().Any(a => a is MethodInterceptAttribute));

            return isDecorated;
        }
Exemple #9
0
        public void GetTypeAspectConfigurationReturnsConfigurationWhenTypeIsRegistered()
        {
            var configuration =
                new AspectConfiguration(ServiceDescriptor.Scoped(typeof(ITestInterface), MyTestInterface.Type));

            inMemoryAspectConfigurationProvider.AddEntry(configuration);
            inMemoryAspectConfigurationProvider.GetTypeAspectConfiguration(configuration.ServiceDescriptor.ServiceType,
                                                                           configuration.ServiceDescriptor.ImplementationType !).Should().NotBeNull();
        }
        protected override void SetAspectConfiguration(AspectConfiguration aspectConfiguration)
        {
            base.SetAspectConfiguration(aspectConfiguration);

            LogAspectConfiguration configuration = (LogAspectConfiguration)aspectConfiguration;
            configuration.OnEntryOptions = this.onEntryOptions;
            configuration.OnSuccessOptions = this.onSuccessOptions;
            configuration.OnExceptionOptions = this.onExceptionOptions;
        }
Exemple #11
0
        public void ShouldInterceptReturnsFalseWhenRegistrationFoundButNoAspectsRegistered()
        {
            var configuration =
                new AspectConfiguration(ServiceDescriptor.Scoped(typeof(ITestInterface), MyTestInterface.Type));

            inMemoryAspectConfigurationProvider.AddEntry(configuration);
            inMemoryAspectConfigurationProvider.ShouldIntercept(MyTestInterface.Type, typeof(ITestInterface),
                                                                MyTestInterface.Type, MyTestInterface.Type.GetMethods().First()).Should().BeFalse();
        }
 protected override void SetAspectConfiguration(AspectConfiguration aspectConfiguration, System.Reflection.MethodBase targetMethod)
 {
     LogAspectConfiguration configuration = (LogAspectConfiguration)aspectConfiguration;
     configuration.OnEntryOptions = this.onEntryOptions;
     configuration.OnSuccessOptions = this.onSuccessOptions;
     configuration.OnExceptionOptions = this.onExceptionOptions;
     configuration.OnEntryLevel = this.onEntryLevel;
     configuration.OnSuccessLevel = this.onSuccessLevel;
     configuration.OnExceptionLevel = this.onExceptionLevel;
 }
Exemple #13
0
        public void AddEntryReplacesExistingEntry()
        {
            var configuration =
                new AspectConfiguration(ServiceDescriptor.Scoped(typeof(ITestInterface), MyTestInterface.Type));

            inMemoryAspectConfigurationProvider.AddEntry(configuration);
            inMemoryAspectConfigurationProvider.ConfigurationEntries.Count.Should().Be(1);
            inMemoryAspectConfigurationProvider.AddEntry(configuration);
            inMemoryAspectConfigurationProvider.ConfigurationEntries.Count.Should().Be(1);
        }
Exemple #14
0
        protected override void SetAspectConfiguration(AspectConfiguration aspectConfiguration)
        {
            base.SetAspectConfiguration(aspectConfiguration);

            LogAspectConfiguration configuration = (LogAspectConfiguration)aspectConfiguration;

            configuration.OnEntryOptions     = this.onEntryOptions;
            configuration.OnSuccessOptions   = this.onSuccessOptions;
            configuration.OnExceptionOptions = this.onExceptionOptions;
        }
Exemple #15
0
        protected override void SetAspectConfiguration(AspectConfiguration aspectConfiguration, MethodBase targetMethod)
        {
            LogAspectConfiguration configuration = (LogAspectConfiguration)aspectConfiguration;

            configuration.OnEntryOptions     = this.onEntryOptions;
            configuration.OnSuccessOptions   = this.onSuccessOptions;
            configuration.OnExceptionOptions = this.onExceptionOptions;
            configuration.OnEntryLevel       = this.onEntryLevel;
            configuration.OnSuccessLevel     = this.onSuccessLevel;
            configuration.OnExceptionLevel   = this.onExceptionLevel;
        }
        public void TestKeyValueStore()
        {
            var watchAdvice = new MethodWatchAdvice();
            var config      = new AspectConfiguration()
                              .AddAspect(watchAdvice);

            var weaver = new AspectWeaver(config, this);

            weaver.Advice(() => { Thread.Sleep(10); });
            Assert.IsTrue(watchAdvice.TotalElapsed >= TimeSpan.FromMilliseconds(10));
        }
Exemple #17
0
        public void ShouldInterceptReturnsFalseWhenRegistrationFoundButNoMatchingMethodFound()
        {
            var methods       = typeof(ITestInterface).GetMethods();
            var configuration =
                new AspectConfiguration(ServiceDescriptor.Scoped(typeof(ITestInterface), MyTestInterface.Type));

            configuration.AddEntry(MyTestInterface.Type, methodsToIntercept: methods.First());
            inMemoryAspectConfigurationProvider.AddEntry(configuration);
            inMemoryAspectConfigurationProvider
            .ShouldIntercept(MyTestInterface.Type, typeof(ITestInterface), MyTestInterface.Type, methods.Last())
            .Should().BeFalse();
        }
        public void EnsureServicesAreProperlyResolvedWithFactory()
        {
            var configuration = new AspectConfiguration(ServiceDescriptor.Describe(typeof(ITestInterface), typeof(MyTestInterface), ServiceLifetime.Transient));

            configuration.AddEntry(TestAspectFactory.Type);
            aspectConfigurationProviderMock.Setup(x => x.GetTypeAspectConfiguration(typeof(ITestInterface), typeof(MyTestInterface))).Returns(configuration);
            serviceCollection.AddLogging();
            serviceCollection.TryAddTransient <ITestInterface, MyTestInterface>();
            serviceCollection.AddAspectSupport(aspectConfigurationProviderMock.Object);
            aspectConfigurationProviderMock.Verify(x => x.GetTypeAspectConfiguration(typeof(ITestInterface), typeof(MyTestInterface)), Times.Once);
            serviceCollection.BuildServiceProvider().GetService <ITestInterface>().Should().NotBeNull();
        }
Exemple #19
0
        public void ShouldInterceptReturnsTrueWhenAllConditionsAreMet()
        {
            var methods       = typeof(ITestInterface).GetMethods();
            var configuration =
                new AspectConfiguration(ServiceDescriptor.Scoped(typeof(ITestInterface), MyTestInterface.Type));

            configuration.AddEntry(MyTestInterface.Type, methodsToIntercept: methods.First());
            inMemoryAspectConfigurationProvider.AddEntry(configuration);
            inMemoryAspectConfigurationProvider
            .ShouldIntercept(MyTestInterface.Type, typeof(ITestInterface), MyTestInterface.Type, methods.First())
            .Should().BeTrue();
        }
Exemple #20
0
        private void RegisterAspectConfiguration(AspectConfiguration aspectConfiguration)
        {
            if (aspectConfiguration.ServiceDescriptor.ImplementationType != null)
            {
                Services.TryAdd(ServiceDescriptor.Describe(aspectConfiguration.ServiceDescriptor.ImplementationType,
                                                           aspectConfiguration.ServiceDescriptor.ImplementationType,
                                                           aspectConfiguration.ServiceDescriptor.Lifetime));
            }

            Services.Add(ServiceDescriptor.Describe(aspectConfiguration.ServiceDescriptor.ServiceType,
                                                    serviceProvider => InvokeCreateFactory(serviceProvider, aspectConfiguration),
                                                    aspectConfiguration.ServiceDescriptor.Lifetime));
        }
Exemple #21
0
        public void TestInvocationMethod()
        {
            var adviceMock = new Mock <IBeforeAdvice>();

            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <ValueTuple, string> >()))
            .Callback((Invocation <ValueTuple, string> invoc) => {
                Assert.AreEqual("TestInvocationMethod", invoc.MethodName);
                Assert.IsFalse(invoc.IsMethodLookupDone);
                Assert.AreEqual("TestInvocationMethod", invoc.Method.Name);
                Assert.IsTrue(invoc.IsMethodLookupDone);

                Assert.IsNotNull(invoc.GetAttribute <TestMethodAttribute>());
                Assert.IsNull(invoc.GetAttribute <TestClassAttribute>());

                Assert.AreEqual("AspectWeaverTests", invoc.TargetType.Name);
            });
            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <string, string> >()))
            .Callback((Invocation <string, string> invoc) => {
                Assert.AreEqual("TestInvocationMethodCall", invoc.MethodName);
                Assert.IsFalse(invoc.IsMethodLookupDone);
                Assert.AreEqual("TestInvocationMethodCall", invoc.Method.Name);
                Assert.IsTrue(invoc.IsMethodLookupDone);

                Assert.IsNull(invoc.GetAttribute <TestMethodAttribute>());
                Assert.IsNull(invoc.GetAttribute <TestClassAttribute>());

                Assert.AreEqual("AspectWeaverTests", invoc.TargetType.Name);
            });

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            string value = "";

            weaver.Advice(() => value = "2");
            Assert.AreEqual("2", value);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, string> >()), Times.Once);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <string, string> >()), Times.Never);

            value = weaver.Advice(() => "3");
            Assert.AreEqual("3", value);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, string> >()), Times.Exactly(2));
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <string, string> >()), Times.Never);

            value = weaver.Advice("4", (string a) => a, "TestInvocationMethodCall");
            Assert.AreEqual("4", value);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, string> >()), Times.Exactly(2));
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <string, string> >()), Times.Once);
        }
        /// <summary>
        /// Creates and wraps the reference type in a Castle proxy
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="reference">The reference.</param>
        public override void Activate(IContext context, InstanceReference reference)
        {
            if (reference.Instance as IInterceptor == null && reference.Instance as INinjectAspectConfiguration == null)
            {
                Configuration = context.Kernel.Get<INinjectAspectConfiguration>().Configuration;

                QueryTargetType(reference.Instance.GetType());
                var interceptors = context.Kernel.GetAll<IInterceptor>();

                reference.Instance = AspectUtility.CreateProxy(_targetInterface, reference.Instance, interceptors.ToArray());
            }

            base.Activate(context, reference);
        }
        /// <summary>
        ///     The test initialize.
        /// </summary>
        public BaseAspectTests()
        {
            var loggerFactory = new Mock <ILoggerFactory>();

            logger = new Mock <ILogger>();
            loggerFactory.Setup(x => x.CreateLogger(typeof(MyTestInterface).FullName)).Returns(logger.Object);
            var aspectConfigurationProvider = new Mock <IAspectConfigurationProvider>().Object;
            var aspectConfiguration         = new AspectConfiguration(new ServiceDescriptor(ITestInterfaceType, MyTestInterface.Type, ServiceLifetime.Transient));

            aspectConfiguration.AddEntry(TestAspectFactory.Type, methodsToIntercept: ITestInterfaceType.GetMethods());
            aspectConfiguration.AddEntry(TestAspectFactory2.Type, methodsToIntercept: ITestInterfaceType.GetMethods());
            aspectConfigurationProvider.AddEntry(aspectConfiguration);
            instance = BaseAspectTestClass <ITestInterface> .Create(new MyTestInterface(), typeof(MyTestInterface), loggerFactory.Object, aspectConfigurationProvider);
        }
Exemple #24
0
        /// <summary>
        ///     The initialize.
        /// </summary>
        public AspectRegistrationTests()
        {
            services = new ServiceCollection();
            services.AddAspectSupport();
            services.AddTransient <ITestInterface, MyTestInterface>();
            services.AddLogging(x => { x.AddConsole(); });
            IAspectConfigurationProvider aspectConfigurationProvider = new InMemoryAspectConfigurationProvider();
            var aspectConfiguration = new AspectConfiguration(new ServiceDescriptor(IInterfaceType, MyTestInterfaceType, ServiceLifetime.Transient));

            aspectConfiguration.AddEntry(TestAspectFactory.Type, methodsToIntercept: IInterfaceType.GetMethods());
            aspectConfiguration.AddEntry(TestAspectFactory2.Type, methodsToIntercept: IInterfaceType.GetMethods());
            aspectConfigurationProvider.AddEntry(aspectConfiguration);
            services.AddAspectSupport(aspectConfigurationProvider);
        }
Exemple #25
0
        /// <summary>
        /// Determines the type of DynamicProxy that will be created over the given type.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public Type GetInterfaceToProxy(Type type, AspectConfiguration configuration)
        {
            var allInterfaces = type.GetInterfaces();

            IEnumerable<Type> baseClassInterfaces = type.BaseType != null ? type.BaseType.GetInterfaces() : new Type[0];
            IEnumerable<Type> topLevelInterfaces = allInterfaces.Except(baseClassInterfaces);

            if (topLevelInterfaces.Count() == 0)
            {
                var types = new[] { type };
                return types.FirstMatch(configuration.Namespaces);
            }

            return allInterfaces.FirstMatch(configuration.Namespaces);
        }
        public static IKernel AddAspectCoreFacility(this IKernel Kernel, Action <IAspectConfiguration> configure = null)
        {
            if (Kernel == null)
            {
                throw new ArgumentNullException(nameof(Kernel));
            }
            var config = new AspectConfiguration();

            configure?.Invoke(config);
            if (Kernel.GetFacilities().All(x => !(x.GetType() == typeof(AspectCoreFacility))))
            {
                Kernel.AddFacility(new AspectCoreFacility(config));
            }
            return(Kernel);
        }
        public void CreateInterfaceProxyType_Wit_ImplType()
        {
            var configuration = new AspectConfiguration();

            configuration.Interceptors.AddTyped <EnableParameterAspectInterceptor>();
            var validatorBuilder   = new AspectValidatorBuilder(configuration);
            var proxyTypeGenerator = new ProxyTypeGenerator(validatorBuilder);
            var proxyType          = proxyTypeGenerator.CreateInterfaceProxyType(typeof(IFakeOpenGenericService <>), typeof(FakeOpenGenericService <>));
            var instance           = Activator.CreateInstance(proxyType.MakeGenericType(typeof(PocoClass)), new object[] { null, new FakeOpenGenericService <PocoClass>(null) });
            var field          = instance.GetType().GetTypeInfo().GetField("_implementation", BindingFlags.Instance | BindingFlags.NonPublic);
            var targetInstance = field.GetValue(instance);

            Assert.NotEqual(instance, targetInstance);
            Assert.NotEqual(instance.GetType(), targetInstance.GetType());
        }
Exemple #28
0
        public AspectInterceptionModule(AspectConfiguration config)
        {
            Interceptors      = config.Interceptors.ToArray();
            Strategies        = config.Strategies.ToArray();
            IncludeNamespaces = new HashSet <string>(config.IncludeNamespaces, StringComparer.InvariantCultureIgnoreCase);
            ExcludeNamespaces = new HashSet <string>(config.ExcludeNamespaces, StringComparer.InvariantCultureIgnoreCase);
            ExcludeTypes      = new HashSet <string>(config.ExcludeTypes, StringComparer.InvariantCultureIgnoreCase);
            ExcludeAssemblies = new HashSet <string>(config.ExcludeAssemblies, StringComparer.InvariantCultureIgnoreCase);

            IncludeTypes = config.AutowireAspect
                                ? new HashSet <Type>(
                config.Assemblies.Select(LoadAssembly)
                .SelectMany(a => a?.ExportedTypes)
                .Where(t => t?.GetCustomAttribute <AspectAttribute>() != null))
                                : new HashSet <Type>();
        }
Exemple #29
0
        static void FuzzTest()
        {
            var config = new AspectConfiguration();

            config.AddAspect <FuzzerAdvice>();
            config.AddAspect <MethodConsoleTraceAdvice>();

            var service = new NumericService(config);

            Console.WriteLine($"{sep} Begin Fuzz Sum() {sep}");
            for (int i = 0; i < 16; i++)
            {
                service.Sum(0, 0);
            }
            Console.WriteLine($"{sep} End Fuzz {sep}");
        }
Exemple #30
0
        /// <summary>
        /// Determines the type of DynamicProxy that will be created over the given type.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public Type GetInterfaceToProxy(Type type, AspectConfiguration configuration)
        {
            var allInterfaces = type.GetInterfaces();

            var baseClassInterfaces = type.BaseType != null ? type.BaseType.GetInterfaces() : new Type[0];
            var topLevelInterfaces = allInterfaces.Except(baseClassInterfaces);

            var levelInterfaces = topLevelInterfaces as Type[] ?? topLevelInterfaces.ToArray();
            if (!levelInterfaces.Any())
            {
                var types = new[] { type };
                return types.FirstMatch(configuration.Namespaces);
            }

            return levelInterfaces.ToArray().FirstMatch(configuration.Namespaces);
        }
Exemple #31
0
        static void Main(string[] args)
        {
            var container = new UnityContainer();

            AspectConfiguration.Setup(container);

            AspectConfiguration.RegisterType <SomeClass>();

            var someClass = container.Resolve <SomeClass>();

            Console.WriteLine(someClass.SomeMethod());

            Console.WriteLine(someClass.SomeMethod());


            Console.ReadLine();
        }
Exemple #32
0
        /// <inheritdoc />
        public IAspectRegistrationBuilder AddService(Type service, Func <IServiceProvider, object> factory,
                                                     ServiceLifetime serviceLifetime)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }
            var aspectConfiguration = new AspectConfiguration(new ServiceDescriptor(service, factory, serviceLifetime));

            AspectConfigurationProvider.AddEntry(aspectConfiguration);
            Services.Add(new ServiceDescriptor(service,
                                               serviceProvider => InvokeCreateFactory(serviceProvider, aspectConfiguration), serviceLifetime));
            return(this);
        }
Exemple #33
0
        /// <summary>
        ///     The test initialize.
        /// </summary>
        public LoggingAspectTests()
        {
            loggerFactory = new Mock <ILoggerFactory>();
            logger        = new Mock <ILogger>();
            aspectConfigurationProvider = new InMemoryAspectConfigurationProvider();
            var aspectConfiguration = new AspectConfiguration(new ServiceDescriptor(AspectRegistrationTests.IInterfaceType, AspectRegistrationTests.MyTestInterfaceType, ServiceLifetime.Transient));

            aspectConfiguration.AddEntry(LoggingAspectFactory.LoggingAspectFactoryType, methodsToIntercept: AspectRegistrationTests.IInterfaceType.GetMethods());
            aspectConfiguration.AddEntry(LoggingAspectFactory.LoggingAspectFactoryType, methodsToIntercept: AspectRegistrationTests.IInterfaceType.GetMethods());
            aspectConfigurationProvider.AddEntry(aspectConfiguration);
            loggerFactory.Setup(x => x.CreateLogger(typeof(MyTestInterface).FullName)).Returns(logger.Object);
            instance = LoggingAspect <ITestInterface> .Create(
                new MyTestInterface(),
                typeof(MyTestInterface),
                loggerFactory.Object,
                aspectConfigurationProvider,
                LoggingAspectFactory.LoggingAspectFactoryType);
        }
Exemple #34
0
        public void TestBasicAfterAdvice()
        {
            var adviceMock = new Mock <IAfterAdvice>();

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            string value = "";

            weaver.Advice(() => { value = "called"; });
            Assert.AreEqual("called", value);

            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Never);

            weaver.Advice("called2", arg => { value = arg; });
            Assert.AreEqual("called2", value);

            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <string, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Never);

            weaver.Advice(() => { value = "called3"; });
            Assert.AreEqual("called3", value);
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Exactly(2));
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <string, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Never);

            weaver.Advice(() => { return(value = "called3"); });
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Exactly(2));
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, string> >()), Times.Once);
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <string, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Never);

            Assert.ThrowsException <Exception>(() => {
                weaver.Advice(() => { throw new Exception(); });
            });
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Exactly(2));
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <ValueTuple, string> >()), Times.Once);
            adviceMock.Verify(a => a.AfterReturning(It.IsAny <Invocation <string, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Once);
        }
Exemple #35
0
        public void TestBeforeAdviceAbort()
        {
            var adviceMock = new Mock <IBeforeAdvice>();

            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()))
            .Callback(() => throw new InvalidOperationException());
            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <int, ValueTuple> >()))
            .Callback(() => { });

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            weaver.Advice(15, n => { });
            Assert.ThrowsException <InvalidOperationException>(() => {
                weaver.Advice(() => { });
            });
        }
Exemple #36
0
        public void TestThrowException()
        {
            var adviceMock = new Mock <IAfterAdvice>();
            var config     = new AspectConfiguration()
                             .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            Assert.ThrowsException <InvalidOperationException>(() => {
                weaver.Advice(() => throw new InvalidOperationException());
            });
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Once);

            Assert.ThrowsException <InvalidOperationException>(() => {
                weaver.Advice(0, p => throw new InvalidOperationException());
            });
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <int, ValueTuple> >(), ref It.Ref <Exception> .IsAny), Times.Once);

            Assert.ThrowsException <InvalidOperationException>(() => {
                weaver.Advice(() => {
                    int a = 0;
                    if (a == 0)
                    {
                        throw new InvalidOperationException();
                    }
                    return(0);
                });
            });
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <ValueTuple, int> >(), ref It.Ref <Exception> .IsAny), Times.Once);

            Assert.ThrowsException <InvalidOperationException>(() => {
                weaver.Advice(0, p => {
                    if (p == 0)
                    {
                        throw new InvalidOperationException();
                    }
                    return(0);
                });
            });
            adviceMock.Verify(a => a.AfterThrowing(It.IsAny <Invocation <int, int> >(), ref It.Ref <Exception> .IsAny), Times.Once);
        }
Exemple #37
0
        public void TestSkipCall()
        {
            var adviceMock = new Mock <IBeforeAdvice>();

            adviceMock.Setup(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()))
            .Callback((Invocation <ValueTuple, ValueTuple> invoc) => invoc.SkipMethod());

            var config = new AspectConfiguration()
                         .AddAspect(adviceMock.Object);

            var weaver = new AspectWeaver(config, this);

            weaver.Advice(() => throw new NotSupportedException());
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);

            Assert.ThrowsException <NotSupportedException>(() => {
                weaver.Advice(0, (int a) => throw new NotSupportedException());
            });
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <ValueTuple, ValueTuple> >()), Times.Once);
            adviceMock.Verify(a => a.Before(It.IsAny <Invocation <int, ValueTuple> >()), Times.Once);
        }
Exemple #38
0
        /// <summary>
        /// Determines the type of DynamicProxy that will be created over the given type.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public Type GetInterfaceToProxy(Type type, AspectConfiguration configuration)
        {
            var allInterfaces = type.GetInterfaces();

            IEnumerable<Type> baseClassInterfaces = type.BaseType != null ? type.BaseType.GetInterfaces() : new Type[0];
            IEnumerable<Type> topLevelInterfaces = allInterfaces.Except(baseClassInterfaces);

            if (topLevelInterfaces.Count() == 0)
            {
                var types = new[] { type };
                return types.FirstMatch(configuration.Namespaces);
            }
            else
            {
                //If the top level interface inherits from the baseclassinterface, then return the top one since that's more specific
                var top = topLevelInterfaces.ToArray().FirstMatch(configuration.Namespaces);
                var bi = baseClassInterfaces.ToArray().FirstMatch(configuration.Namespaces);
                if (top != null && bi != null && top.GetInterfaces().Contains(bi))
                    return top;
            }

            return allInterfaces.FirstMatch(configuration.Namespaces);
        }
Exemple #39
0
 public TypeScanner(AspectConfiguration configuration)
 {
     _configuration = configuration;
 }
Exemple #40
0
 /// <summary>
 /// Sets the container's configuration.
 /// </summary>
 /// <param name="config">The config.</param>
 public abstract void SetConfiguration(AspectConfiguration config);
 /// <summary>
 /// Sets the configuration.
 /// </summary>
 /// <param name="config">The config.</param>
 public override void SetConfiguration(AspectConfiguration config)
 {
     _interceptor.Configuration = config;
     Proxy.Configuration = config;
     config.Container = this;
 }
 /// <summary>
 /// Sets the aspect configuration.
 /// </summary>
 /// <param name="config">The config.</param>
 public override void SetConfiguration(AspectConfiguration config)
 {
     Proxy.Configuration = config;
     Builder.RegisterInstance((MasterProxy)Proxy);
     config.Container = this;
 }
 /// <summary>
 /// Sets the container's configuration.
 /// </summary>
 /// <param name="config">The config.</param>
 public override void SetConfiguration(AspectConfiguration config)
 {
     config.Container = this;
     Proxy.Configuration = config;
 }
 public override void SetConfiguration(AspectConfiguration config)
 {
     _container.AddService("SnapAspectConfiguration", config);
     Proxy.Configuration = config;
     config.Container = this;
 }
 public void SetConfiguration(AspectConfiguration config)
 {
     AspectConfiguration = config;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SnapFluentConfiguration"/> class.
 /// </summary>
 /// <param name="config">The config.</param>
 public SnapFluentConfiguration(AspectConfiguration config)
 {
     _configuration = config;
 }