public void ServicesWithSameServiceTypeButDifferentConditionsAreEqual()
        {
            var service1 = new DecoratorService(typeof(string), ctx => (string)ctx.CurrentInstance == "A");
            var service2 = new DecoratorService(typeof(string), ctx => (string)ctx.CurrentInstance == "B");

            Assert.Equal(service1, service2);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Decorate all components implementing open generic service <paramref name="serviceType"/>.
        /// </summary>
        /// <param name="builder">Container builder.</param>
        /// <param name="decoratorType">The type of the decorator. Must be an open generic type, and accept a parameter
        /// of type <paramref name="serviceType"/>, which will be set to the instance being decorated.</param>
        /// <param name="serviceType">Service type being decorated. Must be an open generic type.</param>
        /// <param name="condition">A function that when provided with an <see cref="IDecoratorContext"/>
        /// instance determines if the decorator should be applied.</param>
        public static void RegisterGenericDecorator(
            this ContainerBuilder builder,
            Type decoratorType,
            Type serviceType,
            Func <IDecoratorContext, bool>?condition = null)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (decoratorType == null)
            {
                throw new ArgumentNullException(nameof(decoratorType));
            }

            if (serviceType == null)
            {
                throw new ArgumentNullException(nameof(serviceType));
            }

            var decoratorService = new DecoratorService(serviceType, condition);

            var genericRegistration = OpenGenericRegistrationExtensions
                                      .CreateGenericBuilder(decoratorType)
                                      .As(decoratorService);

            builder.RegisterServiceMiddlewareSource(new OpenGenericDecoratorMiddlewareSource(decoratorService, genericRegistration.RegistrationData, genericRegistration.ActivatorData));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Decorate all components implementing service <paramref name="serviceType"/>
        /// with decorator service <paramref name="decoratorType"/>.
        /// </summary>
        /// <param name="builder">Container builder.</param>
        /// <param name="decoratorType">Service type of the decorator. Must accept a parameter
        /// of type <paramref name="serviceType"/>, which will be set to the instance being decorated.</param>
        /// <param name="serviceType">Service type being decorated.</param>
        /// <param name="condition">A function that when provided with an <see cref="IDecoratorContext"/>
        /// instance determines if the decorator should be applied.</param>
        public static void RegisterDecorator(
            this ContainerBuilder builder,
            Type decoratorType,
            Type serviceType,
            Func <IDecoratorContext, bool>?condition = null)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (decoratorType == null)
            {
                throw new ArgumentNullException(nameof(decoratorType));
            }

            if (serviceType == null)
            {
                throw new ArgumentNullException(nameof(serviceType));
            }

            var decoratorService = new DecoratorService(serviceType, condition);

            var rb = RegistrationBuilder.ForType(decoratorType).As(decoratorService);

            var decoratorRegistration = rb.CreateRegistration();

            var middleware = new DecoratorMiddleware(decoratorService, decoratorRegistration);

            builder.RegisterServiceMiddleware(serviceType, middleware, MiddlewareInsertionMode.StartOfPhase);

            // Add the decorator to the registry so the pipeline gets built.
            builder.RegisterCallback(crb => crb.Register(decoratorRegistration));
        }
Ejemplo n.º 4
0
        /// <inheritdoc />
        public IEnumerable <IComponentRegistration> DecoratorsFor(IComponentRegistration registration)
        {
            if (registration == null)
            {
                throw new ArgumentNullException(nameof(registration));
            }

            return(_decorators.GetOrAdd(registration, r =>
            {
                var result = new List <IComponentRegistration>();

                foreach (var service in r.Services)
                {
                    if (service is DecoratorService || !(service is IServiceWithType swt))
                    {
                        continue;
                    }

                    var decoratorService = new DecoratorService(swt.ServiceType);
                    var decoratorRegistrations = RegistrationsFor(decoratorService);
                    result.AddRange(decoratorRegistrations);
                }

                return result.OrderBy(d => d.GetRegistrationOrder()).ToArray();
            }));
        }
        public void ServicesGetHashCodeAreEqualWhenServiceTypeMatches()
        {
            var service1 = new DecoratorService(typeof(string));
            var service2 = new DecoratorService(typeof(string));

            Assert.Equal(service1.GetHashCode(), service2.GetHashCode());
        }
        public void ServicesAreEqualWhenServiceTypeMatches()
        {
            var service1 = new DecoratorService(typeof(string));
            var service2 = new DecoratorService(typeof(string));

            Assert.Equal(service1, service2);
        }
        public void ConditionDefaultsToTrueWhenNotProvided()
        {
            var service = new DecoratorService(typeof(string));

            var context = DecoratorContext.Create(typeof(string), typeof(string), "A");

            Assert.True(service.Condition(context));
        }
Ejemplo n.º 8
0
        public void ResolveOperationDoesNotImplementIDependencyTrackingResolveOperation_DecoratorMiddlewareStoppedEarly()
        {
            var decoratorService = new DecoratorService(typeof(object));
            var middleware       = new DecoratorMiddleware(decoratorService, Mock.Of <IComponentRegistration>());
            var contextMock      = new Mock <ResolveRequestContext>();
            var registrationMock = new Mock <IComponentRegistration>();

            contextMock.Setup(context => context.Instance).Returns(new object());
            contextMock.Setup(context => context.Registration).Returns(registrationMock.Object);
            registrationMock.Setup(registration => registration.Options).Returns(RegistrationOptions.None);

            middleware.Execute(contextMock.Object, context => { });

            contextMock.Verify(context => context.Instance, Times.Once);
            contextMock.Verify(context => context.Registration.Options, Times.Once);

            // never got further because IResolveOperation is not of type IDependencyTrackingResolveOperation
            contextMock.Verify(context => context.Service, Times.Never);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Decorate all components implementing service <typeparamref name="TService"/>
        /// using the provided <paramref name="decorator"/> function.
        /// </summary>
        /// <typeparam name="TService">Service type being decorated.</typeparam>
        /// <param name="builder">Container builder.</param>
        /// <param name="decorator">Function decorating a component instance that provides
        /// <typeparamref name="TService"/>, given the context, parameters and service to decorate.</param>
        /// <param name="condition">A function that when provided with an <see cref="IDecoratorContext"/>
        /// instance determines if the decorator should be applied.</param>
        public static void RegisterDecorator <TService>(
            this ContainerBuilder builder,
            Func <IComponentContext, IEnumerable <Parameter>, TService, TService> decorator,
            Func <IDecoratorContext, bool>?condition = null)
            where TService : class
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (decorator == null)
            {
                throw new ArgumentNullException(nameof(decorator));
            }

            var service = new DecoratorService(typeof(TService), condition);

            var rb = RegistrationBuilder.ForDelegate((c, p) =>
            {
                TService?instance = (TService?)p
                                    .OfType <TypedParameter>()
                                    .FirstOrDefault(tp => tp.Type == typeof(TService))
                                    ?.Value;

                if (instance == null)
                {
                    throw new DependencyResolutionException(string.Format(CultureInfo.CurrentCulture, RegistrationExtensionsResources.DecoratorRequiresInstanceParameter, typeof(TService).Name));
                }

                return(decorator(c, p, instance));
            }).As(service);

            var decoratorRegistration = rb.CreateRegistration();

            var middleware = new DecoratorMiddleware(service, decoratorRegistration);

            builder.RegisterServiceMiddleware <TService>(middleware, MiddlewareInsertionMode.StartOfPhase);

            // Add the decorator to the registry so the pipeline gets built.
            builder.RegisterCallback(crb => crb.Register(decoratorRegistration));
        }
        /// <summary>
        /// Decorate all components implementing service <typeparamref name="TService"/>
        /// with decorator service <typeparamref name="TDecorator"/>.
        /// </summary>
        /// <typeparam name="TDecorator">Service type of the decorator. Must accept a parameter
        /// of type <typeparamref name="TService"/>, which will be set to the instance being decorated.</typeparam>
        /// <typeparam name="TService">Service type being decorated.</typeparam>
        /// <param name="builder">Container builder.</param>
        /// <param name="condition">A function that when provided with an <see cref="IDecoratorContext"/>
        /// instance determines if the decorator should be applied.</param>
        public static void RegisterDecorator <[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TDecorator, TService>(this ContainerBuilder builder, Func <IDecoratorContext, bool>?condition = null)
            where TDecorator : notnull, TService
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            var decoratorService = new DecoratorService(typeof(TService), condition);

            var rb = RegistrationBuilder.ForType <TDecorator>().As(decoratorService);

            var decoratorRegistration = rb.CreateRegistration();

            var middleware = new DecoratorMiddleware(decoratorService, decoratorRegistration);

            builder.RegisterServiceMiddleware <TService>(middleware, MiddlewareInsertionMode.StartOfPhase);

            // Add the decorator to the registry so the pipeline gets built.
            builder.RegisterCallback(crb => crb.Register(decoratorRegistration));
        }
Ejemplo n.º 11
0
        public void Decorate_members()
        {
            var service   = Substitute.For <IOrganizationService>();
            var decorator = new DecoratorService(service);

            service.Received(0).Create(Arg.Any <Entity>());
            decorator.Create(new Entity());
            service.Received(1).Create(Arg.Any <Entity>());

            service.Received(0).Retrieve(Arg.Any <string>(), Arg.Any <Guid>(), Arg.Any <ColumnSet>());
            decorator.Retrieve("entity_name", Guid.NewGuid(), new ColumnSet());
            service.Received(1).Retrieve(Arg.Any <string>(), Arg.Any <Guid>(), Arg.Any <ColumnSet>());

            service.Received(0).Update(Arg.Any <Entity>());
            decorator.Update(new Entity());
            service.Received(1).Update(Arg.Any <Entity>());

            service.Received(0).Delete(Arg.Any <string>(), Arg.Any <Guid>());
            decorator.Delete("entity_name", Guid.NewGuid());
            service.Received(1).Delete(Arg.Any <string>(), Arg.Any <Guid>());

            service.Received(0).Execute(Arg.Any <OrganizationRequest>());
            decorator.Execute(new OrganizationRequest());
            service.Received(1).Execute(Arg.Any <OrganizationRequest>());

            service.Received(0).Associate(Arg.Any <string>(), Arg.Any <Guid>(), Arg.Any <Relationship>(), Arg.Any <EntityReferenceCollection>());
            decorator.Associate("entity_name", Guid.NewGuid(), new Relationship(), new EntityReferenceCollection());
            service.Received(1).Associate(Arg.Any <string>(), Arg.Any <Guid>(), Arg.Any <Relationship>(), Arg.Any <EntityReferenceCollection>());

            service.Received(0).Disassociate(Arg.Any <string>(), Arg.Any <Guid>(), Arg.Any <Relationship>(), Arg.Any <EntityReferenceCollection>());
            decorator.Disassociate("entity_name", Guid.NewGuid(), new Relationship(), new EntityReferenceCollection());
            service.Received(1).Disassociate(Arg.Any <string>(), Arg.Any <Guid>(), Arg.Any <Relationship>(), Arg.Any <EntityReferenceCollection>());

            service.Received(0).RetrieveMultiple(Arg.Any <QueryBase>());
            decorator.RetrieveMultiple(new QueryExpression());
            service.Received(1).RetrieveMultiple(Arg.Any <QueryBase>());
        }
 public DecoratorService_Tests()
 {
     _resolverContextMock = Substitute.For <IResolverContext>();
     Sut = new DecoratorService();
 }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            Console.WriteLine(string.Format("ed = {0}, Tom = {1}", "cool", "less cool"));
            //SRP
            Console.WriteLine("SRP");
            UserStorage  s = new UserStorage();
            EmailStorage e = new EmailStorage();

            SRPService main = new SRPService(s, e);

            Console.WriteLine("_________________________________");
            Console.WriteLine("OCP");
            //OCP
            OCPService ocp = new OCPService();

            Console.WriteLine("_________________________________");
            Console.WriteLine("LSP");
            //LSP
            LSPService lsp = new LSPService();

            Console.WriteLine("_________________________________");
            Console.WriteLine("ISP");
            //ISP
            ISPService isp = new ISPService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("DIP");
            //DIP
            DIPService sip = new DIPService();

            Console.WriteLine("_________________________________");
            Console.WriteLine("Law of Demeter");
            //Law of demeter
            Demeter dim = new Demeter();

            Console.WriteLine("_________________________________");
            Console.WriteLine("Factory pattern");
            //factory
            FactoryService factory = new FactoryService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("Adaptor Pattern");
            //Adaptor pattern
            AdaptorService adaptorService = new AdaptorService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("Decorator Pattern");
            //decorator pattern
            DecoratorService decoratorService = new DecoratorService();

            Console.WriteLine("_________________________________");


            Console.WriteLine("Repository Pattern");
            //Repository pattern
            RepositoryService RepositoryService = new RepositoryService();

            Console.WriteLine("_________________________________");


            Console.WriteLine("Tree Traversal");
            //BinaryTree Traversal
            BinaryTreeService BinaryTreeService = new BinaryTreeService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("Number Swap");
            //Number Swap
            NumberSwapService NumberSwapService = new NumberSwapService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("Multiply");
            //Multiply
            MultiplyService MultiplyService = new MultiplyService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("OverflowChecked");
            //OverflowCheckedService
            OverflowCheckedService OverflowChecked = new OverflowCheckedService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("By Ref");
            //pass by reference
            ByRefService ByRefService = new ByRefService();

            Console.WriteLine("_________________________________");

            Console.WriteLine(" EF Code FirstService");
            //EFCodeFirstService
            //EFCodeFirstService EFCodeFirstService = new EFCodeFirstService();
            Console.WriteLine("_________________________________");
            //read
            Console.ReadLine();
        }