private static string UniqueComponentName(Microsoft.Extensions.DependencyInjection.ServiceDescriptor service)
 {
     return
         ((service.ImplementationType?.FullName ??
           service.ImplementationInstance?.GetType().FullName ??
           service.ImplementationFactory.GetType().FullName
           ) + "@" + Guid.NewGuid().ToString());
 }
Example #2
0
 public static void AddIfNot <TService, TImplement>(this IServiceCollection services, ServiceLifetime lifetime)
     where TImplement : class, TService
 {
     Throw.IfArgumentNull(services, nameof(services));
     if (!services.IsRegistered(typeof(TService)))
     {
         services.Add(ServiceDescriptor.Describe(typeof(TService), typeof(TImplement), lifetime));
     }
 }
Example #3
0
        public static void AddDecorator <TService, TDecorator>(this IServiceCollection services,
                                                               ServiceLifetime lifetime = ServiceLifetime.Scoped)
            where TService : class
            where TDecorator : class
        {
            var serviceDescriptor = new ServiceDescriptor(
                typeof(TService),
                provider => Construct <TService, TDecorator>(provider, services), lifetime);

            services.Add(serviceDescriptor);
        }
 public static IRegistration CreateWindsorRegistration(this Microsoft.Extensions.DependencyInjection.ServiceDescriptor service)
 {
     if (service.ServiceType.ContainsGenericParameters)
     {
         return(RegistrationAdapter.FromOpenGenericServiceDescriptor(service));
     }
     else
     {
         var method = typeof(RegistrationAdapter).GetMethod("FromServiceDescriptor", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(service.ServiceType);
         return(method.Invoke(null, new object[] { service }) as IRegistration);
     }
 }
        private void RegisterWindsor(Microsoft.Extensions.DependencyInjection.ServiceDescriptor item)
        {
            try
            {
                ComponentRegistration <object> r = null;
                if (item.ImplementationType != null)
                {
                    if (_container.Kernel.HasComponent(item.ImplementationType))
                    {
                        return;
                    }
                    r = Component.For(item.ServiceType).ImplementedBy(item.ImplementationType);
                }
                else if (item.ImplementationFactory != null)
                {
                    var provider = WindsorRegistrationHelper.CreateServiceProvider(_container, this);
                    r = Component.For(item.ServiceType).UsingFactoryMethod(() => item.ImplementationFactory.Invoke(provider));
                }
                else if (item.ImplementationInstance != null)
                {
                    r = Component.For(item.ServiceType).UsingFactoryMethod(() => item.ImplementationInstance);
                }

                if (item.Lifetime == ServiceLifetime.Scoped)
                {
                    _container.Register(r.LifestyleScoped());
                }
                else if (item.Lifetime == ServiceLifetime.Transient)
                {
                    _container.Register(r.LifestyleTransient());
                }
                else if (item.Lifetime == ServiceLifetime.Singleton)
                {
                    _container.Register(r.LifestyleSingleton());
                }
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("Component Microsoft.Extensions.Options.OptionsManager`1 could not be registered") &&
                    !ex.Message.Contains("Component Late bound Microsoft.Extensions.Options.IConfigureOptions`1[[Microsoft.Extensions.Logging.LoggerFilterOptions, Microsoft.Extensions.Logging"))
                {
                    // Known issue at: https://gist.github.com/cwe1ss/050a531e2711f5b62ab0
                    throw;
                }
            }
        }
Example #6
0
        public static IRegistration FromOpenGenericServiceDescriptor(Microsoft.Extensions.DependencyInjection.ServiceDescriptor service)
        {
            ComponentRegistration <object> registration = Component.For(service.ServiceType)
                                                          .NamedAutomatically(UniqueComponentName(service));

            if (service.ImplementationType != null)
            {
                registration = UsingImplementation(registration, service);
            }
            else
            {
                throw new System.ArgumentException("Unsupported ServiceDescriptor");
            }

            return(ResolveLifestyle(registration, service)
                   .IsDefault());
        }
Example #7
0
        private static void MultipleImplementationWithReplace()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddTransient <IHasValue, MyClassWithValue>();
            services.Replace(ServiceDescriptor.Transient <IHasValue, MyClassWithValue2>());

            var serviceProvider = services.BuildServiceProvider();
            var myServices      = serviceProvider.GetServices <IHasValue>().ToList();

            System.Console.WriteLine("----- Multiple Implemantation Replace ------------");

            foreach (var service in myServices)
            {
                System.Console.WriteLine(service.Value);
            }

            System.Console.WriteLine("--------------------------------------------------");
        }
Example #8
0
        private static void RegisterServiceDescriptor(IWindsorContainer container, ServiceDescriptor serviceDescriptor)
        {
            // MS allows the same type to be registered multiple times.
            // Castle Windsor throws an exception in that case - it requires an unique name.
            // For that reason, we use Guids to ensure uniqueness.
            string uniqueName = serviceDescriptor.ServiceType.FullName + "_" + Guid.NewGuid();

            // The IsDefault() calls are important because this makes sure that the last service
            // is returned in case of multiple registrations. This is by design in the MS library:
            // https://github.com/aspnet/DependencyInjection/blob/dev/src/Microsoft.Extensions.DependencyInjection.Specification.Tests/DependencyInjectionSpecificationTests.cs#L254

            if (serviceDescriptor.ImplementationType != null)
            {
                container.Register(
                    Component.For(serviceDescriptor.ServiceType)
                    .Named(uniqueName)
                    .IsDefault()
                    .ImplementedBy(serviceDescriptor.ImplementationType)
                    .ConfigureLifecycle(serviceDescriptor.Lifetime));
            }
            else if (serviceDescriptor.ImplementationFactory != null)
            {
                var serviceDescriptorRef = serviceDescriptor;
                container.Register(
                    Component.For(serviceDescriptor.ServiceType)
                    .Named(uniqueName)
                    .IsDefault()
                    .UsingFactoryMethod(c => serviceDescriptorRef.ImplementationFactory(c.Resolve <IServiceProvider>()))
                    .ConfigureLifecycle(serviceDescriptor.Lifetime)
                    );
            }
            else
            {
                container.Register(
                    Component.For(serviceDescriptor.ServiceType)
                    .Named(uniqueName)
                    .IsDefault()
                    .Instance(serviceDescriptor.ImplementationInstance)
                    .ConfigureLifecycle(serviceDescriptor.Lifetime)
                    );
            }
        }
Example #9
0
        internal static string UniqueComponentName(Microsoft.Extensions.DependencyInjection.ServiceDescriptor service)
        {
            var result = "";

            if (service.ImplementationType != null)
            {
                result = service.ImplementationType.FullName;
            }
            else if (service.ImplementationInstance != null)
            {
                result = service.ImplementationInstance.GetType().FullName;
            }
            else
            {
                result = service.ImplementationFactory.GetType().FullName;
            }
            result = result + "@" + Guid.NewGuid().ToString();

            return(result);
        }
Example #10
0
        public static IRegistration FromServiceDescriptor(Microsoft.Extensions.DependencyInjection.ServiceDescriptor service)
        {
            var registration = Component.For(service.ServiceType)
                               .NamedAutomatically(UniqueComponentName(service));

            if (service.ImplementationFactory != null)
            {
                registration = UsingFactoryMethod(registration, service);
            }
            else if (service.ImplementationInstance != null)
            {
                registration = UsingInstance(registration, service);
            }
            else if (service.ImplementationType != null)
            {
                registration = UsingImplementation(registration, service);
            }

            return(ResolveLifestyle(registration, service)
                   .IsDefault());
        }
 public int IndexOf(Microsoft.Extensions.DependencyInjection.ServiceDescriptor item)
 {
     return(_descriptors.IndexOf(item));
 }
 void ICollection <Microsoft.Extensions.DependencyInjection.ServiceDescriptor> .Add(Microsoft.Extensions.DependencyInjection.ServiceDescriptor item)
 {
     RegisterWindsor(item);
     _descriptors.Add(item);
 }
 /// <inheritdoc />
 public bool Remove(Microsoft.Extensions.DependencyInjection.ServiceDescriptor item)
 {
     return(_descriptors.Remove(item));
 }
 /// <inheritdoc />
 public bool Contains(Microsoft.Extensions.DependencyInjection.ServiceDescriptor item)
 {
     return(_descriptors.Contains(item));
 }
Example #15
0
 private static ComponentRegistration <TService> UsingFactoryMethod <TService>(ComponentRegistration <TService> registration, Microsoft.Extensions.DependencyInjection.ServiceDescriptor service) where TService : class
 {
     return(registration.UsingFactoryMethod((kernel) => {
         var serviceProvider = kernel.Resolve <System.IServiceProvider>();
         return service.ImplementationFactory(serviceProvider) as TService;
     }));
 }
 public void Insert(int index, Microsoft.Extensions.DependencyInjection.ServiceDescriptor item)
 {
     RegisterWindsor(item);
     _descriptors.Insert(index, item);
 }
Example #17
0
        public static IMetricsHostBuilder AddGlobalFilter(this IMetricsHostBuilder builder, IMetricsFilter filter)
        {
            builder.Services.Replace(ServiceDescriptor.Singleton(filter));

            return(builder);
        }
 public static IServiceCollection ReplaceConfiguration(this IServiceCollection services, IConfiguration configuration)
 {
     return(services.Replace(ServiceDescriptor.Singleton <IConfiguration>(configuration)));
 }
Example #19
0
 private static void AddOpenTelemetryInternal(IServiceCollection services)
 {
     services.TryAddEnumerable(ServiceDescriptor.Singleton <IHostedService, TelemetryHostedService>());
 }
        // To enable unit testing
        internal static void AddMvcCoreServices(IServiceCollection services)
        {
            //
            // Options
            //
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <MvcOptions>, MvcCoreMvcOptionsSetup>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IPostConfigureOptions <MvcOptions>, MvcCoreMvcOptionsSetup>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <ApiBehaviorOptions>, ApiBehaviorOptionsSetup>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <RouteOptions>, MvcCoreRouteOptionsSetup>());

            //
            // Action Discovery
            //
            // These are consumed only when creating action descriptors, then they can be deallocated
            services.TryAddSingleton <ApplicationModelFactory>();
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IApplicationModelProvider, DefaultApplicationModelProvider>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IApplicationModelProvider, ApiBehaviorApplicationModelProvider>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IActionDescriptorProvider, ControllerActionDescriptorProvider>());

            services.TryAddSingleton <IActionDescriptorCollectionProvider, DefaultActionDescriptorCollectionProvider>();

            //
            // Action Selection
            //
            services.TryAddSingleton <IActionSelector, ActionSelector>();
            services.TryAddSingleton <ActionConstraintCache>();

            // Will be cached by the DefaultActionSelector
            services.TryAddEnumerable(ServiceDescriptor.Transient <IActionConstraintProvider, DefaultActionConstraintProvider>());

            // Policies for Endpoints
            services.TryAddEnumerable(ServiceDescriptor.Singleton <MatcherPolicy, ActionConstraintMatcherPolicy>());

            //
            // Controller Factory
            //
            // This has a cache, so it needs to be a singleton
            services.TryAddSingleton <IControllerFactory, DefaultControllerFactory>();

            // Will be cached by the DefaultControllerFactory
            services.TryAddTransient <IControllerActivator, DefaultControllerActivator>();

            services.TryAddSingleton <IControllerFactoryProvider, ControllerFactoryProvider>();
            services.TryAddSingleton <IControllerActivatorProvider, ControllerActivatorProvider>();
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IControllerPropertyActivator, DefaultControllerPropertyActivator>());

            //
            // Action Invoker
            //
            // The IActionInvokerFactory is cachable
            services.TryAddSingleton <IActionInvokerFactory, ActionInvokerFactory>();
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IActionInvokerProvider, ControllerActionInvokerProvider>());

            // These are stateless
            services.TryAddSingleton <ControllerActionInvokerCache>();
            services.TryAddEnumerable(
                ServiceDescriptor.Singleton <IFilterProvider, DefaultFilterProvider>());
            services.TryAddSingleton <IActionResultTypeMapper, ActionResultTypeMapper>();

            //
            // Request body limit filters
            //
            services.TryAddTransient <RequestSizeLimitFilter>();
            services.TryAddTransient <DisableRequestSizeLimitFilter>();
            services.TryAddTransient <RequestFormLimitsFilter>();

            //
            // ModelBinding, Validation
            //
            // The DefaultModelMetadataProvider does significant caching and should be a singleton.
            services.TryAddSingleton <IModelMetadataProvider, DefaultModelMetadataProvider>();
            services.TryAdd(ServiceDescriptor.Transient <ICompositeMetadataDetailsProvider>(s =>
            {
                var options = s.GetRequiredService <IOptions <MvcOptions> >().Value;
                return(new DefaultCompositeMetadataDetailsProvider(options.ModelMetadataDetailsProviders));
            }));
            services.TryAddSingleton <IModelBinderFactory, ModelBinderFactory>();
            services.TryAddSingleton <IObjectModelValidator>(s =>
            {
                var options          = s.GetRequiredService <IOptions <MvcOptions> >().Value;
                var metadataProvider = s.GetRequiredService <IModelMetadataProvider>();
                return(new DefaultObjectValidator(metadataProvider, options.ModelValidatorProviders, options));
            });
            services.TryAddSingleton <ClientValidatorCache>();
            services.TryAddSingleton <ParameterBinder>();

            //
            // Random Infrastructure
            //
            services.TryAddSingleton <MvcMarkerService, MvcMarkerService>();
            services.TryAddSingleton <ITypeActivatorCache, TypeActivatorCache>();
            services.TryAddSingleton <IUrlHelperFactory, UrlHelperFactory>();
            services.TryAddSingleton <IHttpRequestStreamReaderFactory, MemoryPoolHttpRequestStreamReaderFactory>();
            services.TryAddSingleton <IHttpResponseStreamWriterFactory, MemoryPoolHttpResponseStreamWriterFactory>();
            services.TryAddSingleton(ArrayPool <byte> .Shared);
            services.TryAddSingleton(ArrayPool <char> .Shared);
            services.TryAddSingleton <OutputFormatterSelector, DefaultOutputFormatterSelector>();
            services.TryAddSingleton <IActionResultExecutor <ObjectResult>, ObjectResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <PhysicalFileResult>, PhysicalFileResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <VirtualFileResult>, VirtualFileResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <FileStreamResult>, FileStreamResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <FileContentResult>, FileContentResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <RedirectResult>, RedirectResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <LocalRedirectResult>, LocalRedirectResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <RedirectToActionResult>, RedirectToActionResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <RedirectToRouteResult>, RedirectToRouteResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <RedirectToPageResult>, RedirectToPageResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <ContentResult>, ContentResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <JsonResult>, SystemTextJsonResultExecutor>();
            services.TryAddSingleton <IClientErrorFactory, ProblemDetailsClientErrorFactory>();
            services.TryAddSingleton <ProblemDetailsFactory, DefaultProblemDetailsFactory>();

            //
            // Route Handlers
            //
            services.TryAddSingleton <MvcRouteHandler>();          // Only one per app
            services.TryAddTransient <MvcAttributeRouteHandler>(); // Many per app

            //
            // Endpoint Routing / Endpoints
            //
            services.TryAddSingleton <ControllerActionEndpointDataSourceFactory>();
            services.TryAddSingleton <OrderedEndpointsSequenceProviderCache>();
            services.TryAddSingleton <ControllerActionEndpointDataSourceIdProvider>();
            services.TryAddSingleton <ActionEndpointFactory>();
            services.TryAddSingleton <DynamicControllerEndpointSelectorCache>();
            services.TryAddEnumerable(ServiceDescriptor.Singleton <MatcherPolicy, DynamicControllerEndpointMatcherPolicy>());
            services.TryAddEnumerable(ServiceDescriptor.Singleton <IRequestDelegateFactory, ControllerRequestDelegateFactory>());

            //
            // Middleware pipeline filter related
            //
            services.TryAddSingleton <MiddlewareFilterConfigurationProvider>();
            // This maintains a cache of middleware pipelines, so it needs to be a singleton
            services.TryAddSingleton <MiddlewareFilterBuilder>();
            // Sets ApplicationBuilder on MiddlewareFilterBuilder
            services.TryAddEnumerable(ServiceDescriptor.Singleton <IStartupFilter, MiddlewareFilterBuilderStartupFilter>());
        }
Example #21
0
 private static IServiceCollection Add(this IServiceCollection services, ServiceDefinition service)
 {
     services.Add(ServiceDescriptor.Describe(service.ServiceType, service.ImplementationType, service.Lifetime));
     return(services);
 }
        // Internal for testing.
        internal static void AddViewServices(IServiceCollection services)
        {
            services.AddDataProtection();
            services.AddAntiforgery();
            services.AddWebEncoders();

            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <MvcViewOptions>, MvcViewOptionsSetup>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <MvcOptions>, TempDataMvcOptionsSetup>());

            //
            // View Engine and related infrastructure
            //
            services.TryAddSingleton <ICompositeViewEngine, CompositeViewEngine>();
            services.TryAddSingleton <IActionResultExecutor <ViewResult>, ViewResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <PartialViewResult>, PartialViewResultExecutor>();

            // Support for activating ViewDataDictionary
            services.TryAddEnumerable(
                ServiceDescriptor
                .Transient <IControllerPropertyActivator, ViewDataDictionaryControllerPropertyActivator>());

            //
            // HTML Helper
            //
            services.TryAddTransient <IHtmlHelper, HtmlHelper>();
            services.TryAddTransient(typeof(IHtmlHelper <>), typeof(HtmlHelper <>));
            services.TryAddSingleton <IHtmlGenerator, DefaultHtmlGenerator>();
            services.TryAddSingleton <ModelExpressionProvider>();
            // ModelExpressionProvider caches results. Ensure that it's re-used when the requested type is IModelExpressionProvider.
            services.TryAddSingleton <IModelExpressionProvider>(s => s.GetRequiredService <ModelExpressionProvider>());
            services.TryAddSingleton <ValidationHtmlAttributeProvider, DefaultValidationHtmlAttributeProvider>();

            services.TryAddSingleton <IJsonHelper, SystemTextJsonHelper>();

            // Component services for Blazor server-side interop
            services.TryAddSingleton <ServerComponentSerializer>();

            // Component services for Blazor webassembly interop
            services.TryAddSingleton <WebAssemblyComponentSerializer>();

            //
            // View Components
            //

            // These do caching so they should stay singleton
            services.TryAddSingleton <IViewComponentSelector, DefaultViewComponentSelector>();
            services.TryAddSingleton <IViewComponentFactory, DefaultViewComponentFactory>();
            services.TryAddSingleton <IViewComponentActivator, DefaultViewComponentActivator>();
            services.TryAddSingleton <
                IViewComponentDescriptorCollectionProvider,
                DefaultViewComponentDescriptorCollectionProvider>();
            services.TryAddSingleton <IActionResultExecutor <ViewComponentResult>, ViewComponentResultExecutor>();

            services.TryAddSingleton <ViewComponentInvokerCache>();
            services.TryAddTransient <IViewComponentDescriptorProvider, DefaultViewComponentDescriptorProvider>();
            services.TryAddSingleton <IViewComponentInvokerFactory, DefaultViewComponentInvokerFactory>();
            services.TryAddTransient <IViewComponentHelper, DefaultViewComponentHelper>();

            //
            // Temp Data
            //
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IApplicationModelProvider, TempDataApplicationModelProvider>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IApplicationModelProvider, ViewDataAttributeApplicationModelProvider>());
            services.TryAddSingleton <SaveTempDataFilter>();

            //
            // Component rendering
            //
            services.TryAddScoped <IComponentRenderer, ComponentRenderer>();
            services.TryAddScoped <StaticComponentRenderer>();
            services.TryAddScoped <HtmlRenderer>();
            services.TryAddScoped <NavigationManager, HttpNavigationManager>();
            services.TryAddScoped <IJSRuntime, UnsupportedJavaScriptRuntime>();
            services.TryAddScoped <INavigationInterception, UnsupportedNavigationInterception>();
            services.TryAddScoped <ComponentApplicationLifetime>();
            services.TryAddScoped <ComponentApplicationState>(sp => sp.GetRequiredService <ComponentApplicationLifetime>().State);

            services.TryAddTransient <ControllerSaveTempDataPropertyFilter>();

            // This does caching so it should stay singleton
            services.TryAddSingleton <ITempDataProvider, CookieTempDataProvider>();
            services.TryAddSingleton <TempDataSerializer, DefaultTempDataSerializer>();

            //
            // Antiforgery
            //
            services.TryAddSingleton <ValidateAntiforgeryTokenAuthorizationFilter>();
            services.TryAddSingleton <AutoValidateAntiforgeryTokenAuthorizationFilter>();

            // These are stateless so their lifetime isn't really important.
            services.TryAddSingleton <ITempDataDictionaryFactory, TempDataDictionaryFactory>();
            services.TryAddSingleton(ArrayPool <ViewBufferValue> .Shared);
            services.TryAddScoped <IViewBufferScope, MemoryPoolViewBufferScope>();
        }
Example #23
0
 public static FluentEmailServicesBuilder AddMailKitSender(this FluentEmailServicesBuilder builder, SmtpClientOptions smtpClientOptions)
 {
     builder.Services.TryAdd(ServiceDescriptor.Scoped <ISender>(x => new MailKitSender(smtpClientOptions)));
     return(builder);
 }
Example #24
0
 public static IServiceCollection AddHttpClientNewtonsoftJosn(this IServiceCollection services)
 {
     services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IHttpContentSerializer), typeof(NewtonsoftJosnContentSerializer)));
     services.PostConfigure <JsonSerializerSettings>(i => { });
     return(services);
 }
Example #25
0
        // Internal for testing.
        internal static void AddViewServices(IServiceCollection services)
        {
            services.AddDataProtection();
            services.AddAntiforgery();
            services.AddWebEncoders();

            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <MvcViewOptions>, MvcViewOptionsSetup>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <MvcOptions>, TempDataMvcOptionsSetup>());

            //
            // View Engine and related infrastructure
            //
            services.TryAddSingleton <ICompositeViewEngine, CompositeViewEngine>();
            services.TryAddSingleton <ViewResultExecutor>();
            services.TryAddSingleton <PartialViewResultExecutor>();

            // Support for activating ViewDataDictionary
            services.TryAddEnumerable(
                ServiceDescriptor
                .Transient <IControllerPropertyActivator, ViewDataDictionaryControllerPropertyActivator>());

            //
            // HTML Helper
            //
            services.TryAddTransient <IHtmlHelper, HtmlHelper>();
            services.TryAddTransient(typeof(IHtmlHelper <>), typeof(HtmlHelper <>));
            services.TryAddSingleton <IHtmlGenerator, DefaultHtmlGenerator>();

            //
            // JSON Helper
            //
            services.TryAddSingleton <IJsonHelper, JsonHelper>();
            services.TryAdd(ServiceDescriptor.Singleton <JsonOutputFormatter>(serviceProvider =>
            {
                var options  = serviceProvider.GetRequiredService <IOptions <MvcJsonOptions> >().Value;
                var charPool = serviceProvider.GetRequiredService <ArrayPool <char> >();
                return(new JsonOutputFormatter(options.SerializerSettings, charPool));
            }));

            //
            // View Components
            //

            // These do caching so they should stay singleton
            services.TryAddSingleton <IViewComponentSelector, DefaultViewComponentSelector>();
            services.TryAddSingleton <IViewComponentFactory, DefaultViewComponentFactory>();
            services.TryAddSingleton <IViewComponentActivator, DefaultViewComponentActivator>();
            services.TryAddSingleton <
                IViewComponentDescriptorCollectionProvider,
                DefaultViewComponentDescriptorCollectionProvider>();

            services.TryAddSingleton <ViewComponentInvokerCache>();
            services.TryAddTransient <IViewComponentDescriptorProvider, DefaultViewComponentDescriptorProvider>();
            services.TryAddSingleton <IViewComponentInvokerFactory, DefaultViewComponentInvokerFactory>();
            services.TryAddTransient <IViewComponentHelper, DefaultViewComponentHelper>();

            //
            // Temp Data
            //
            // This does caching so it should stay singleton
            services.TryAddSingleton <ITempDataProvider, SessionStateTempDataProvider>();

            //
            // Antiforgery
            //
            services.TryAddSingleton <ValidateAntiforgeryTokenAuthorizationFilter>();
            services.TryAddSingleton <AutoValidateAntiforgeryTokenAuthorizationFilter>();

            // These are stateless so their lifetime isn't really important.
            services.TryAddSingleton <ITempDataDictionaryFactory, TempDataDictionaryFactory>();
            services.TryAddSingleton <SaveTempDataFilter>();

            services.TryAddSingleton(ArrayPool <ViewBufferValue> .Shared);
            services.TryAddScoped <IViewBufferScope, MemoryPoolViewBufferScope>();
        }
Example #26
0
 /// <summary>
 /// Registers the <see cref="WsFederationHandler"/> using the given authentication scheme, display name, and options configuration.
 /// </summary>
 /// <param name="builder"></param>
 /// <param name="authenticationScheme"></param>
 /// <param name="displayName"></param>
 /// <param name="configureOptions">A delegate that configures the <see cref="WsFederationOptions"/>.</param>
 /// <returns></returns>
 public static AuthenticationBuilder AddWsFederation(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action <WsFederationOptions> configureOptions)
 {
     builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IPostConfigureOptions <WsFederationOptions>, WsFederationPostConfigureOptions>());
     return(builder.AddRemoteScheme <WsFederationOptions, WsFederationHandler>(authenticationScheme, displayName, configureOptions));
 }
Example #27
0
 private static ComponentRegistration <TService> UsingImplementation <TService>(ComponentRegistration <TService> registration, Microsoft.Extensions.DependencyInjection.ServiceDescriptor service) where TService : class
 {
     return(registration.ImplementedBy(service.ImplementationType));
 }
Example #28
0
 /// <summary>
 /// Adds cookie authentication to <see cref="AuthenticationBuilder"/> using the specified scheme.
 /// <para>
 /// Cookie authentication uses a HTTP cookie persisted in the client to perform authentication.
 /// </para>
 /// </summary>
 /// <param name="builder">The <see cref="AuthenticationBuilder"/>.</param>
 /// <param name="authenticationScheme">The authentication scheme.</param>
 /// <param name="displayName">A display name for the authentication handler.</param>
 /// <param name="configureOptions">A delegate to configure <see cref="CookieAuthenticationOptions"/>.</param>
 /// <returns>A reference to <paramref name="builder"/> after the operation has completed.</returns>
 public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme, string?displayName, Action <CookieAuthenticationOptions> configureOptions)
 {
     builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IPostConfigureOptions <CookieAuthenticationOptions>, PostConfigureCookieAuthenticationOptions>());
     builder.Services.AddOptions <CookieAuthenticationOptions>(authenticationScheme).Validate(o => o.Cookie.Expiration == null, "Cookie.Expiration is ignored, use ExpireTimeSpan instead.");
     return(builder.AddScheme <CookieAuthenticationOptions, CookieAuthenticationHandler>(authenticationScheme, displayName, configureOptions));
 }
Example #29
0
        private static ComponentRegistration <TService> ResolveLifestyle <TService>(ComponentRegistration <TService> registration, Microsoft.Extensions.DependencyInjection.ServiceDescriptor service) where TService : class
        {
            switch (service.Lifetime)
            {
            case ServiceLifetime.Singleton:
                return(registration.LifeStyle.NetStatic());

            case ServiceLifetime.Scoped:
                return(registration.LifeStyle.ScopedToNetServiceScope());

            case ServiceLifetime.Transient:
                return(registration.LifestyleNetTransient());

            default:
                throw new System.ArgumentException($"Invalid lifetime {service.Lifetime}");
            }
        }
Example #30
0
        // Internal for testing.
        internal static void AddRazorViewEngineServices(IServiceCollection services)
        {
            services.TryAddSingleton <CSharpCompiler>();
#pragma warning disable CS0618 // Type or member is obsolete
            services.TryAddSingleton <RazorReferenceManager, DefaultRazorReferenceManager>();
#pragma warning restore CS0618 // Type or member is obsolete

            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <MvcViewOptions>, MvcRazorMvcViewOptionsSetup>());

            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <RazorViewEngineOptions>, RazorViewEngineOptionsSetup>());

            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IPostConfigureOptions <RazorViewEngineOptions>, RazorViewEngineOptionsSetup>());

            services.TryAddSingleton <
                IRazorViewEngineFileProviderAccessor,
                DefaultRazorViewEngineFileProviderAccessor>();

            services.TryAddSingleton <IRazorViewEngine>(s =>
            {
                var pageFactory      = s.GetRequiredService <IRazorPageFactoryProvider>();
                var pageActivator    = s.GetRequiredService <IRazorPageActivator>();
                var htmlEncoder      = s.GetRequiredService <HtmlEncoder>();
                var optionsAccessor  = s.GetRequiredService <IOptions <RazorViewEngineOptions> >();
                var razorFileSystem  = s.GetRequiredService <RazorProjectFileSystem>();
                var loggerFactory    = s.GetRequiredService <ILoggerFactory>();
                var diagnosticSource = s.GetRequiredService <DiagnosticSource>();

                var viewEngine = new RazorViewEngine(pageFactory, pageActivator, htmlEncoder, optionsAccessor, razorFileSystem, loggerFactory, diagnosticSource);
                return(viewEngine);
            });
            services.TryAddSingleton <IViewCompilerProvider, RazorViewCompilerProvider>();
            services.TryAddSingleton <IViewCompilationMemoryCacheProvider, RazorViewCompilationMemoryCacheProvider>();

            // In the default scenario the following services are singleton by virtue of being initialized as part of
            // creating the singleton RazorViewEngine instance.
            services.TryAddTransient <IRazorPageFactoryProvider, DefaultRazorPageFactoryProvider>();

            //
            // Razor compilation infrastructure
            //
            services.TryAddSingleton <LazyMetadataReferenceFeature>();
            services.TryAddSingleton <RazorProjectFileSystem, FileProviderRazorProjectFileSystem>();
            services.TryAddSingleton(s =>
            {
                var fileSystem    = s.GetRequiredService <RazorProjectFileSystem>();
                var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
                {
                    RazorExtensions.Register(builder);

                    // Roslyn + TagHelpers infrastructure
                    var metadataReferenceFeature = s.GetRequiredService <LazyMetadataReferenceFeature>();
                    builder.Features.Add(metadataReferenceFeature);
                    builder.Features.Add(new CompilationTagHelperFeature());

                    // TagHelperDescriptorProviders (actually do tag helper discovery)
                    builder.Features.Add(new DefaultTagHelperDescriptorProvider());
                    builder.Features.Add(new ViewComponentTagHelperDescriptorProvider());
                });

                return(projectEngine);
            });

            // Legacy Razor compilation services
            services.TryAddSingleton <RazorProject>(s => s.GetRequiredService <RazorProjectEngine>().FileSystem);
            services.TryAddSingleton <RazorTemplateEngine, MvcRazorTemplateEngine>();
            services.TryAddSingleton(s => s.GetRequiredService <RazorProjectEngine>().Engine);

            // This caches Razor page activation details that are valid for the lifetime of the application.
            services.TryAddSingleton <IRazorPageActivator, RazorPageActivator>();

            // Only want one ITagHelperActivator and ITagHelperComponentPropertyActivator so it can cache Type activation information. Types won't conflict.
            services.TryAddSingleton <ITagHelperActivator, DefaultTagHelperActivator>();
            services.TryAddSingleton <ITagHelperComponentPropertyActivator, TagHelperComponentPropertyActivator>();

            services.TryAddSingleton <ITagHelperFactory, DefaultTagHelperFactory>();

            // TagHelperComponents manager
            services.TryAddScoped <ITagHelperComponentManager, TagHelperComponentManager>();

            // Consumed by the Cache tag helper to cache results across the lifetime of the application.
            services.TryAddSingleton <IMemoryCache, MemoryCache>();
            services.TryAddSingleton <TagHelperMemoryCacheProvider>();
        }