Exemplo n.º 1
0
        static ServiceDescriptor WithUrlHelperFactoryDecorator(IServiceCollection services)
        {
            var descriptor = services.FirstOrDefault(sd => sd.ServiceType == typeof(IUrlHelperFactory));
            var lifetime   = ServiceLifetime.Singleton;
            Func <IServiceProvider, object> instantiate = sp => new UrlHelperFactory();

            if (descriptor != null)
            {
                lifetime    = descriptor.Lifetime;
                instantiate = sp => sp.CreateInstance(descriptor);
            }

            IUrlHelperFactory NewFactory(IServiceProvider serviceProvider)
            {
                var decorated = instantiate(serviceProvider);
                var source    = serviceProvider.GetRequiredService <IApiVersionParameterSource>();
                var instance  = decorated;

                if (source.VersionsByUrlSegment())
                {
                    var factory = ActivatorUtilities.CreateFactory(typeof(ApiVersionUrlHelperFactory), new[] { typeof(IUrlHelperFactory) });
                    instance = factory(serviceProvider, new[] { decorated });
                }

                return((IUrlHelperFactory)instance);
            }

            return(Describe(typeof(IUrlHelperFactory), NewFactory, lifetime));
        }
        public void SetUp()
        {
            var collection = new ServiceCollection();

            collection.AddTransient <TypeToBeActivated>();
            collection.AddSingleton <DependencyA>();
            collection.AddSingleton <DependencyB>();
            collection.AddSingleton <DependencyC>();
            collection.AddTransient <TypeToBeActivated>();

            _serviceProvider  = collection.BuildServiceProvider();
            _factory          = ActivatorUtilities.CreateFactory(typeof(TypeToBeActivated), new Type[] { typeof(DependencyB), typeof(DependencyC) });
            _factoryArguments = new object[] { new DependencyB(), new DependencyC() };
        }
Exemplo n.º 3
0
        static ServiceDescriptor WithUrlHelperFactoryDecorator(IServiceCollection services)
        {
            var descriptor = services.First(sd => sd.ServiceType == typeof(IUrlHelperFactory));
            var factory    = ActivatorUtilities.CreateFactory(typeof(ApiVersionUrlHelperFactory), new[] { typeof(IUrlHelperFactory) });

            IUrlHelperFactory NewFactory(IServiceProvider serviceProvider)
            {
                var decorated = serviceProvider.CreateInstance(descriptor !);
                var options   = serviceProvider.GetRequiredService <IOptions <ApiVersioningOptions> >().Value;
                var instance  = options.ApiVersionReader.VersionsByUrlSegment() ?
                                factory(serviceProvider, new[] { decorated }) :
                                decorated;

                return((IUrlHelperFactory)instance);
            }

            return(Describe(typeof(IUrlHelperFactory), NewFactory, descriptor.Lifetime));
        }