Exemple #1
0
        public static IWebHostBuilder UseDefaultServiceProvider(this IWebHostBuilder hostBuilder, Action <WebHostBuilderContext, ServiceProviderOptions> configure)
        {
            // Light up the GenericWebHostBuilder implementation
            if (hostBuilder is ISupportsUseDefaultServiceProvider supportsDefaultServiceProvider)
            {
                return(supportsDefaultServiceProvider.UseDefaultServiceProvider(configure));
            }

            return(hostBuilder.ConfigureServices((context, services) =>
            {
                var options = new ServiceProviderOptions();
                configure(context, options);
                services.Replace(ServiceDescriptor.Singleton <IServiceProviderFactory <IServiceCollection> >(new DefaultServiceProviderFactory(options)));
            }));
        }
Exemple #2
0
        public DependencyManager(DiscordSocketClient client)
        {
            var collection = new ServiceCollection();

            foreach (var type in Assembly.GetExecutingAssembly().DefinedTypes)
            {
                if (!type.TryGetAttribute(out ServiceAttribute? service))
                {
                    continue;
                }

                switch (service.Scope)
                {
                case ServiceScope.Singleton:
                    collection.AddSingleton(type, type);
                    break;

                case ServiceScope.Scoped:
                    collection.AddScoped(type, type);
                    break;

                case ServiceScope.Transient:
                    collection.AddTransient(type, type);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            collection
            .AddSingleton(client)
            .AddLavaNode(c =>
            {
                c.SelfDeaf = false;
                c.Hostname = EnvironmentKey.Lavahost.GetOrThrow();
                c.Port     = 8080;
            });

            var options = new ServiceProviderOptions
            {
                ValidateScopes  = true,
                ValidateOnBuild = true
            };

            ServiceProvider = collection.BuildServiceProvider(options);
            SetDependencies(collection);
        }
        public static IServiceProvider GetServiceProvider(
            Action <IServiceCollection> servicesConfigurationAction)
        {
            var services = new ServiceCollection();

            services.AddSingleton(Substitute.For <IHostApplicationLifetime>());

            servicesConfigurationAction(services);

            var options = new ServiceProviderOptions {
                ValidateScopes = true
            };
            var serviceProvider = services.BuildServiceProvider(options);

            return(serviceProvider.CreateScope().ServiceProvider);
        }
        public IGameHostBuilder UseDefaultServiceProvider(Action <GameHostBuilderContext, ServiceProviderOptions> configure)
        {
#if NET2
            throw new NotImplementedException();
#else
            _builder.UseServiceProviderFactory(context =>
            {
                var gameHostBuilderContext = GetGameHostBuilderContext(context);
                var options = new ServiceProviderOptions();
                configure(gameHostBuilderContext, options);
                return(new DefaultServiceProviderFactory(options));
            });
#endif

            return(this);
        }
        public IWebHostBuilder UseDefaultServiceProvider(Action <WebHostBuilderContext, ServiceProviderOptions> configure)
        {
            // REVIEW: This is a hack to change the builder with the HostBuilderContext in scope,
            // we're not actually using configuration here
            _builder.ConfigureAppConfiguration((context, _) =>
            {
                var webHostBuilderContext = GetWebHostBuilderContext(context);
                var options = new ServiceProviderOptions();
                configure(webHostBuilderContext, options);

                // This is only fine because this runs last
                _builder.UseServiceProviderFactory(new DefaultServiceProviderFactory(options));
            });

            return(this);
        }
Exemple #6
0
 static void BuildServiceProvider(bool validateOnBuild)
 {
     try
     {
         var options = new ServiceProviderOptions
         {
             ValidateOnBuild = validateOnBuild
         };
         new ServiceCollection()
         .AddSingleton <IFoobar, Foobar>()
         .BuildServiceProvider(options);
         Console.WriteLine($"Status: Success; ValidateOnBuild: {validateOnBuild}");
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Status: Fail; ValidateOnBuild: {validateOnBuild}");
         Console.WriteLine($"Error: {ex.Message}");
     }
 }
        /// <summary>
        /// Apply interception machanism to dependency injection framework.
        /// </summary>
        /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to build service host.</param>
        /// <param name="serviceProviderOptions">The options for configuring various behaviors of the default <see cref="IServiceProvider"/> implementation.</param>
        /// <param name="setup">The <see cref="Action{InterceptionBuilder}"/> to perform advanced service registrations.</param>
        /// <returns>The current <see cref="IHostBuilder"/>.</returns>
        public static IHostBuilder UseInterception(this IHostBuilder hostBuilder, ServiceProviderOptions serviceProviderOptions, Action <InterceptionBuilder>?setup = null)
        {
            if (hostBuilder == null)
            {
                throw new ArgumentNullException(nameof(hostBuilder));
            }
            if (serviceProviderOptions == null)
            {
                throw new ArgumentNullException(nameof(serviceProviderOptions));
            }
            hostBuilder.ConfigureServices((_, services) => services.AddHttpContextAccessor());
            Action <InterceptionBuilder> configure = builder =>
            {
                builder.Services.Replace(ServiceDescriptor.Singleton <IInvocationServiceScopeFactory, RequestServiceScopeFactory>());
                setup?.Invoke(builder);
            };

            return(hostBuilder.UseServiceProviderFactory(new InterceptionServiceProviderFactory(serviceProviderOptions ?? new ServiceProviderOptions(), configure)));
        }
Exemple #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ServicesBuilder" /> class.
 /// </summary>
 /// <param name="scanner">The scanner.</param>
 /// <param name="assemblyProvider">The assembly provider.</param>
 /// <param name="assemblyCandidateFinder">The assembly candidate finder.</param>
 /// <param name="services">The services.</param>
 /// <param name="configuration">The configuration.</param>
 /// <param name="environment">The environment.</param>
 /// <param name="diagnosticSource">The diagnostic source.</param>
 /// <param name="properties">The properties.</param>
 /// <exception cref="ArgumentNullException">
 /// environment
 /// or
 /// diagnosticSource
 /// or
 /// configuration
 /// or
 /// services
 /// </exception>
 public ServicesBuilder(
     IConventionScanner scanner,
     IAssemblyProvider assemblyProvider,
     IAssemblyCandidateFinder assemblyCandidateFinder,
     IServiceCollection services,
     IConfiguration configuration,
     IRocketEnvironment environment,
     ILogger diagnosticSource,
     IDictionary <object, object?> properties
     )
     : base(scanner, assemblyProvider, assemblyCandidateFinder, properties)
 {
     Environment            = environment ?? throw new ArgumentNullException(nameof(environment));
     Configuration          = configuration ?? throw new ArgumentNullException(nameof(configuration));
     Services               = services ?? throw new ArgumentNullException(nameof(services));
     Logger                 = diagnosticSource ?? throw new ArgumentNullException(nameof(diagnosticSource));
     _onBuild               = new ServiceProviderObservable(Logger);
     ServiceProviderOptions = new ServiceProviderOptions
     {
         ValidateScopes = environment.IsDevelopment()
     };
 }
Exemple #9
0
        static void Main(string[] args)
        {
            try
            {
                var serviceCollection = new ServiceCollection();
                ConfigureServices(serviceCollection);

                var options = new ServiceProviderOptions
                {
                    ValidateOnBuild = true,
                    ValidateScopes  = true
                };

                using var serviceProvider = serviceCollection.BuildServiceProvider(options);
                var logger = serviceProvider.GetRequiredService <ILogger <Program> >();

                try
                {
                    var sdl = serviceProvider.GetRequiredService <ISdl2>();
                    var stb = serviceProvider.GetRequiredService <IStb>();

                    var w = int.Parse(args[0]);
                    var h = int.Parse(args[1]);

                    CreateSheetsFromFolder(logger, sdl, stb, new Point32(w, h), args[2], args[3]);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Error building sheet.");
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex);
                Console.ResetColor();
            }
        }
Exemple #10
0
        public ServiceProvider(IServiceCollection descriptors, ServiceProviderOptions options = null)
        {
            if (descriptors == null)
            {
                throw new ArgumentNullException(nameof(descriptors));
            }

            for (int i = 0; i < descriptors.Count; i++)
            {
                var descriptor = descriptors[i];

                if (descriptor.ImplementationType != null && descriptor.ImplementationType.IsInjectable())
                {
                    var method  = GetFacotryMethod.MakeGenericMethod(descriptor.ImplementationType);
                    var factory = (Func <IServiceProvider, object>)method.Invoke(null, Array.Empty <object>());
                    descriptors[i] = new ServiceDescriptor(descriptor.ServiceType, factory, descriptor.Lifetime);
                }
            }

            descriptors.AddSingleton(this);
            descriptors.AddSingleton <IServiceProvider>(this);

            _provider = descriptors.BuildServiceProvider(options);
        }
 public InterceptionServiceProviderFactory(ServiceProviderOptions providerOptions, Action <InterceptionBuilder>?setup)
 {
     _setup           = setup;
     _providerOptions = providerOptions;
 }
Exemple #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CoreHostServiceProviderFactory"/> class
 /// with default options.
 /// </summary>
 /// <seealso cref="ServiceProviderOptions"/>
 public CoreHostServiceProviderFactory()
 {
     _options = new ServiceProviderOptions();
 }
 public static ServiceProvider BuildServiceProvider(this IServiceCollection collection, ServiceProviderOptions options)
 {
     return(new ServiceProvider(collection, options));
 }
 public MicrosoftDependencyInjection(IServiceCollection serviceCollection, IServiceScope scope = null, ServiceProviderOptions options = null)
 {
     _serviceCollection = serviceCollection;
     _scope             = scope;
     _options           = options ?? new ServiceProviderOptions {
         ValidateScopes = true
     };
 }
Exemple #15
0
 /// <summary>
 /// Create a new <see cref="InterceptableServiceProviderFactory"/>.
 /// </summary>
 /// <param name="options">Options for configuring various behaviors of the default <see cref="IServiceProvider"/> implementation.</param>
 /// <param name="configure">The <see cref="Action{InterceptionBuilder}"/> used to perform more service registrations.</param>
 public InterceptableServiceProviderFactory(ServiceProviderOptions options, Action <InterceptionBuilder> configure)
 {
     _configure = configure;
     _options   = options;
 }
Exemple #16
0
 public ServiceCollectionDependencyResolver(IServiceCollection services, ServiceProviderOptions serviceProviderOptions)
 {
     _services        = services ?? throw new ArgumentNullException(nameof(services));
     _serviceProvider = services.BuildServiceProvider(serviceProviderOptions ?? new ServiceProviderOptions());
 }
 public ServiceCollectionDependencyResolver(IServiceCollection services, ServiceProviderOptions serviceProviderOptions) : this(services.BuildServiceProvider(serviceProviderOptions ?? new ServiceProviderOptions()))
 {
 }
Exemple #18
0
        /// <summary>
        /// Creates an <see cref="IServiceProvider"/> containing services from the provided <see cref="IServiceCollection"/>
        /// optionaly enabling scope validation.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/> containing service descriptors.</param>
        /// <param name="options">
        /// Configures various service provider behaviors.
        /// </param>
        /// <returns>The <see cref="IServiceProvider"/>.</returns>
        public static ServiceProvider BuildServiceProvider(this AliceServiceCollection services, ServiceProviderOptions options)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

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

            return(new ServiceProvider(services, options));
        }
        private static HostBuilder CreateDefaultBuilder(string[] args)
        {
            // Host.CreateDefaultBuilder() is not available before .netcore 3.0.
            // So this is a copied from https://github.com/dotnet/extensions
            var builder = new HostBuilder();

            builder.UseContentRoot(Directory.GetCurrentDirectory());
            builder.ConfigureHostConfiguration(config =>
            {
                config.AddEnvironmentVariables(prefix: "DOTNET_");
                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            });

            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                IHostingEnvironment env = hostingContext.HostingEnvironment;
                env.ApplicationName     = Assembly.GetEntryAssembly()?.GetName().Name;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            });

            builder.ConfigureLogging((hostingContext, logging) =>
            {
                bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

                // IMPORTANT: This needs to be added *before* configuration is loaded, this lets
                // the defaults be overridden by the configuration.
                if (isWindows)
                {
                    // Default the EventLogLoggerProvider to warning or above
                    logging.AddFilter <EventLogLoggerProvider>(level => level >= LogLevel.Warning);
                }

                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();

                if (isWindows)
                {
                    // Add the EventLogLoggerProvider on windows machines
                    logging.AddEventLog();
                }
            });

            var options = new ServiceProviderOptions();

            builder.UseServiceProviderFactory(new DefaultServiceProviderFactory(options));

            return(builder);
        }
Exemple #20
0
 public InterceptableServiceProviderFactory(ServiceProviderOptions options, Action <InterceptionBuilder>?setup)
 {
     _options = options ?? throw new ArgumentNullException(nameof(options));
     _setup   = setup;
 }
Exemple #21
0
 private static void ConfigureServiceProvider(ServiceProviderOptions serviceProvider)
 {
     serviceProvider.ValidateScopes  = true;
     serviceProvider.ValidateOnBuild = true;
 }
Exemple #22
0
        public static ServiceProvider BuildServiceProvider(this IServiceCollection services, ServiceProviderMode mode, ServiceProviderOptions options = null)
        {
            options ??= ServiceProviderOptions.Default;

            if (mode == ServiceProviderMode.Default)
            {
                return(services.BuildServiceProvider(options));
            }

            var provider = new ServiceProvider(services, ServiceProviderOptions.Default);
            ServiceProviderEngine engine = mode switch
            {
                ServiceProviderMode.Dynamic => new DynamicServiceProviderEngine(provider),
                ServiceProviderMode.Runtime => RuntimeServiceProviderEngine.Instance,
                ServiceProviderMode.Expressions => new ExpressionsServiceProviderEngine(provider),
                ServiceProviderMode.ILEmit => new ILEmitServiceProviderEngine(provider),
                _ => throw new NotSupportedException()
            };

            provider._engine = engine;
            return(provider);
        }
    }
Exemple #23
0
 public DynamicProxyServiceProviderFactory(ServiceProviderOptions serviceProviderOptions)
 {
     _serviceProviderOptions = serviceProviderOptions;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ServiceProviderFactory"/> class
 /// with the specified <paramref name="options"/>.
 /// </summary>
 /// <param name="options">The options to use for this instance.</param>
 public ServiceProviderFactory(ServiceProviderOptions options)
 {
     _options = options;
 }
 public static void SetDependencyResolver(IServiceCollection services, ServiceProviderOptions serviceProviderOptions) => SetDependencyResolver(new ServiceCollectionDependencyResolver(services, serviceProviderOptions));
 public static IHostBuilder UseAopServiceProviderFactory(this IHostBuilder hostBuilder, ServiceProviderOptions serviceProviderOptions)
 {
     _ = hostBuilder ?? throw new ArgumentNullException(nameof(hostBuilder));
     return(hostBuilder.UseServiceProviderFactory((buildContext) => new DynamicProxyServiceProviderFactoryWithOptions(serviceProviderOptions)));
 }
Exemple #27
0
 public static ServiceProvider BuildDynamicProxyProvider(this IServiceCollection services, ServiceProviderOptions options)
 {
     return(services.WeaveDynamicProxyService().BuildServiceProvider(options));
 }
 public DynamicProxyServiceProviderFactoryWithOptions(ServiceProviderOptions serviceProviderOptions)
 {
     ServiceProviderOptions = serviceProviderOptions;
 }
 public ServiceProviderFactoryWithServiceLocatorSetup(ServiceProviderOptions options)
 {
     _options = options ?? throw new ArgumentNullException(nameof(options));
 }
        public static IServiceProvider BuildFluentAspectsProvider(this IServiceCollection serviceCollection,
                                                                  Action <FluentAspectOptions> optionsAction,
                                                                  Action <IFluentAspectsBuilder> aspectBuildAction  = null,
                                                                  Expression <Func <Type, bool> > ignoreTypesFilter = null,
                                                                  ServiceProviderOptions serviceProviderOptions     = null)
        {
            IServiceCollection services = new ServiceCollection();

            var aspectBuilder = null != optionsAction
                ? serviceCollection.AddFluentAspects(optionsAction)
                : serviceCollection.AddFluentAspects();

            aspectBuildAction?.Invoke(aspectBuilder);

            Expression <Func <Type, bool> > ignoreTypesExpression = t => "WeihanLi.Common.Aspect".Equals(t.Namespace);

            if (null != ignoreTypesFilter)
            {
                ignoreTypesExpression = ignoreTypesExpression.Or(ignoreTypesFilter);
            }

            var ignoreTypesPredicate = ignoreTypesExpression.Compile();

            using (var serviceProvider = serviceCollection.BuildServiceProvider())
            {
                var proxyTypeFactory = serviceProvider.GetRequiredService <IProxyTypeFactory>();

                foreach (var descriptor in serviceCollection)
                {
                    if (descriptor.ServiceType.IsSealed ||
                        descriptor.ServiceType.IsNotPublic ||
                        descriptor.ServiceType.IsGenericTypeDefinition
                        )
                    {
                        services.Add(descriptor);
                        continue;
                    }

                    if (ignoreTypesPredicate(descriptor.ServiceType))
                    {
                        services.Add(descriptor);
                        continue;
                    }

                    if (descriptor.ImplementationType != null)
                    {
                        if (descriptor.ImplementationType.IsNotPublic ||
                            descriptor.ImplementationType.IsProxyType()
                            )
                        {
                            services.Add(descriptor);
                            continue;
                        }

                        if (descriptor.ServiceType.IsClass &&
                            descriptor.ImplementationType.IsSealed)
                        {
                            services.Add(descriptor);
                            continue;
                        }

                        if (descriptor.ServiceType.IsGenericTypeDefinition ||
                            descriptor.ImplementationType.IsGenericTypeDefinition)
                        {
                            var proxyType = proxyTypeFactory.CreateProxyType(descriptor.ServiceType, descriptor.ImplementationType);
                            services.Add(new ServiceDescriptor(descriptor.ServiceType, proxyType,
                                                               descriptor.Lifetime));
                            continue;
                        }
                    }

                    Func <IServiceProvider, object> serviceFactory = null;

                    if (descriptor.ImplementationInstance != null)
                    {
                        if (descriptor.ImplementationInstance.GetType().IsPublic)
                        {
                            serviceFactory = provider => provider.GetRequiredService <IProxyFactory>()
                                             .CreateProxyWithTarget(descriptor.ServiceType, descriptor.ImplementationInstance);
                        }
                    }
                    else if (descriptor.ImplementationType != null)
                    {
                        serviceFactory = provider =>
                        {
                            var proxy = provider.GetRequiredService <IProxyFactory>()
                                        .CreateProxy(descriptor.ServiceType, descriptor.ImplementationType);
                            return(proxy);
                        };
                    }
                    else if (descriptor.ImplementationFactory != null)
                    {
                        serviceFactory = provider =>
                        {
                            var implement = descriptor.ImplementationFactory(provider);
                            if (implement == null)
                            {
                                return(null);
                            }

                            var implementType = implement.GetType();
                            if (implementType.IsNotPublic ||
                                implementType.IsProxyType())
                            {
                                return(implement);
                            }

                            return(provider.ResolveRequiredService <IProxyFactory>()
                                   .CreateProxyWithTarget(descriptor.ServiceType, implement));
                        };
                    }

                    if (null != serviceFactory)
                    {
                        services.Add(new ServiceDescriptor(descriptor.ServiceType, serviceFactory,
                                                           descriptor.Lifetime));
                    }
                    else
                    {
                        services.Add(descriptor);
                    }
                }
            }

            DependencyResolver.SetDependencyResolver(services);

            return(services.BuildServiceProvider(serviceProviderOptions ?? new ServiceProviderOptions()));
        }