Пример #1
0
        static void Main(string[] args)
        {
            using (var kernel = new StandardKernel())
            {
                // an interceptor can be used to automatically generate decorator classes
                var interceptor = new ActionInterceptor(invocation =>
                {
                    Console.WriteLine("Before " + invocation.Request.Method.DeclaringType.Name + "." + invocation.Request.Method.Name);
                    invocation.Proceed();
                    Console.WriteLine("After" + invocation.Request.Method.DeclaringType.Name + "." + invocation.Request.Method.Name);
                });

                kernel.Bind <InterfaceB>().To <ObjectB>()
                .Intercept().With(interceptor);

                // the benefit is that we can write an interceptor once, not a decorator per interface
                // this is useful for cross-cutting concerns like auditing, logging, etc.
                // gotcha: ObjectC.DoStuff needs to be virtual, since its a concrete class.  the dynamic proxy can only intercept virtual methods.
                kernel.Bind <ObjectC>().ToSelf()
                .Intercept().With(interceptor);

                var a = kernel.Get <ObjectA>();

                a.DoStuff();
            }
        }
        public InterceptorBaseTests()
        {
            _invocationList = new List <string>();

            //using concrete classes because interception did NOT play well with Moq
            _actionInterceptor = new ActionInterceptor()
            {
                PreInvocation                = context => { _invocationList.Add(Pre); return(_PreReturnValue); },
                PostSuccessInvocation        = context => { _invocationList.Add(PostSuccess); },
                PostErrorInvocation          = (ex, context) => { _invocationList.Add(PostError); },
                TransformExceptionInvocation = (ex, context) => { _invocationList.Add(TransformException); return(ex); }
            };

            _businessClasses = new Dictionary <ExceptionMode, IBusinessClass>();

            foreach (var mode in Enum.GetValues(typeof(ExceptionMode)).Cast <ExceptionMode>())
            {
                _businessClasses[mode] = new ActionBusinessClass()
                {
                    SomethingImportantInvocation      = () => { RecordInvocation(nameof(IBusinessClass.SomethingImportant), mode); },
                    SomethingImportantAsyncInvocation = () => { return(RecordInvocationAsync(nameof(IBusinessClass.SomethingImportantAsync), mode)); },

                    FetchSomethingInvocation      = () => { RecordInvocation(nameof(IBusinessClass.FetchSomething), mode); return(ExpectedFetchedValue); },
                    FetchSomethingAsyncInvocation = () => { return(RecordInvocationAsync(nameof(IBusinessClass.FetchSomethingAsync), mode, ExpectedFetchedValue)); }
                };
            }
        }
        public void ActionValueTypeWithSingleParameterInIntercepted <T>(T expectedValue)
            where T : struct
        {
            // Given
            var proxyFactory = Context.ProxyFactory;
            var interceptor  = new ActionInterceptor(true);
            var decoratee    = new FooActionValueTypeParameterIn <T>();

            // When
            var foo = proxyFactory.CreateDecorator <IFooActionValueTypeParameterIn <T> >(decoratee, interceptor);

            foo.MethodWithOneParameter(expectedValue);

            // Then
            Assert.NotNull(foo);
            Assert.Equal(0u, decoratee.CallCount);
            Assert.Empty(decoratee.Parameters);

            Assert.Single(interceptor.ForwardedInvocations);
            var invocation = interceptor.ForwardedInvocations.Single();

            invocation.ShouldInterceptMethodWithName(nameof(IFooActionValueTypeParameterIn <T> .MethodWithOneParameter));
            invocation.ShouldHaveParameterInCountOf(1);
            invocation.ShouldHaveParameterIn("first", typeof(T), expectedValue);
            invocation.ShouldHaveNoParameterRef();
            invocation.ShouldHaveNoParameterOut();
        }
Пример #4
0
        /// <summary>
        /// Adds the method interceptor.
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        /// <param name="method">The method to intercept.</param>
        /// <param name="action">The action to take in its place.</param>
        public static void AddMethodInterceptor(this IKernel kernel,
                                                MethodInfo method,
                                                Action <IInvocation> action)
        {
            var interceptor = new ActionInterceptor(action);

            kernel.Components.Get <IMethodInterceptorRegistry>().Add(method, interceptor);
        }
        public void ActionValueTypeWithSingleParameterRef <T>(T expectedValue)
            where T : struct
        {
            // Given
            var proxyFactory = Context.ProxyFactory;
            var interceptor  = new ActionInterceptor(false);
            var decoratee    = new FooActionValueTypeParameterRef <T>();
            var actualValue  = expectedValue;

            // When
            var foo = proxyFactory.CreateDecorator <IFooActionValueTypeParameterRef <T> >(decoratee, interceptor);

            foo.MethodWithOneParameter(ref actualValue);

            // Then
            Assert.NotNull(foo);
            Assert.Equal(1u, decoratee.CallCount);
            Assert.Equal(expectedValue, decoratee.Parameters.SingleOrDefault());
            Assert.Equal(default, actualValue);
Пример #6
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            ILog logger = LogManager.GetLogger(typeof(Program));

            try
            {
                IKernel kernel = new StandardKernel();


                var interceptor = new ActionInterceptor(invocation =>
                {
                    var sw = new Stopwatch();
                    sw.Start();
                    try
                    {
                        invocation.Proceed();
                    }
                    finally
                    {
                        sw.Stop();
                        logger.DebugFormat("Die Ausführung der Methode {0} dauerte {1} ms",
                                           invocation.Request.Method,
                                           sw.ElapsedMilliseconds);
                    }
                });
                kernel.Bind <IUserRepository>().To <UserRepository>().Intercept()
                .With(interceptor);

                IUserRepository userRepo = kernel.Get <IUserRepository>();

                foreach (var user in userRepo.GetAllUsers())
                {
                    Console.WriteLine("{0}:\t {1} {2}", user.Id, user.FirstName, user.Name);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
            Console.ReadLine();
        }
Пример #7
0
        public void ActionWithoutParameters()
        {
            // Given
            var proxyFactory = Context.ProxyFactory;
            var interceptor  = new ActionInterceptor();

            // When
            var foo = proxyFactory.CreateForInterface <IFooActionParameterless>(interceptor);

            foo.MethodWithoutParameter();

            // Then
            Assert.NotNull(foo);

            Assert.Single(interceptor.ForwardedInvocations);
            var invocation = interceptor.ForwardedInvocations.Single();

            invocation.ShouldInterceptMethodWithName(nameof(IFooActionParameterless.MethodWithoutParameter));
            invocation.ShouldHaveNoParameterIn();
            invocation.ShouldHaveNoParameterRef();
            invocation.ShouldHaveNoParameterOut();
        }
        public void ActionWithoutParametersIntercepted()
        {
            // Given
            var proxyFactory = Context.ProxyFactory;
            var interceptor  = new ActionInterceptor(true);
            var decoratee    = new FooActionParameterless();

            // When
            var foo = proxyFactory.CreateDecorator <IFooActionParameterless>(decoratee, interceptor);

            foo.MethodWithoutParameter();

            // Then
            Assert.NotNull(foo);
            Assert.Equal(0u, decoratee.CallCount);

            Assert.Single(interceptor.ForwardedInvocations);
            var invocation = interceptor.ForwardedInvocations.Single();

            invocation.ShouldInterceptMethodWithName(nameof(IFooActionParameterless.MethodWithoutParameter));
            invocation.ShouldHaveNoParameterIn();
            invocation.ShouldHaveNoParameterRef();
            invocation.ShouldHaveNoParameterOut();
        }
        public void ActionValueTypeWithSingleParameterRef <T>(T expectedValue)
            where T : struct
        {
            // Given
            var proxyFactory = Context.ProxyFactory;
            var interceptor  = new ActionInterceptor();

            // When
            var foo = proxyFactory.CreateForInterface <IFooActionValueTypeParameterRef <T> >(interceptor);

            foo.MethodWithOneParameter(ref expectedValue);

            // Then
            Assert.NotNull(foo);

            Assert.Single(interceptor.ForwardedInvocations);
            var invocation = interceptor.ForwardedInvocations.Single();

            invocation.ShouldInterceptMethodWithName(nameof(IFooActionValueTypeParameterRef <T> .MethodWithOneParameter));
            invocation.ShouldHaveNoParameterIn();
            invocation.ShouldHaveParameterRefCountOf(1);
            invocation.ShouldHaveParameterRef("first", typeof(T), expectedValue);
            invocation.ShouldHaveNoParameterOut();
        }