Exemplo n.º 1
0
        /// <summary>
        /// Provides services from the referenced host application.
        /// Use the <see cref="CreateFrom"/> method instead, it you only need Rhetos context and components.
        /// </summary>
        public static IServiceProvider GetHostServices(
            string rhetosHostAssemblyPath,
            Action <IRhetosHostBuilder> configureRhetosHost = null,
            Action <HostBuilderContext, IServiceCollection> configureServices = null)
        {
            // Using the full path for better error reporting.
            rhetosHostAssemblyPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rhetosHostAssemblyPath));
            if (!File.Exists(rhetosHostAssemblyPath))
            {
                throw new ArgumentException($"Please specify the host application assembly file. File '{rhetosHostAssemblyPath}' does not exist.");
            }

            var hostBuilder = HostResolver.FindBuilder(rhetosHostAssemblyPath);

            hostBuilder.UseContentRoot(Path.GetDirectoryName(rhetosHostAssemblyPath));
            hostBuilder.ConfigureServices((hostContext, services) =>
            {
                services.AddRhetosHost((serviceProvider, rhetosHostBuilder) =>
                {
                    // Overriding Rhetos host application's location settings, because the default values might be incorrect when the host assembly is executed
                    // from another process with FindBuilder. For example, it could have different AppDomain.BaseDirectory, or the assembly copied in shadow directory.
                    rhetosHostBuilder.UseRootFolder(Path.GetDirectoryName(rhetosHostAssemblyPath)); // Use host assembly directory as root for all RhetosHostBuilder operations.
                    rhetosHostBuilder.ConfigureConfiguration(configurationBuilder => configurationBuilder.AddKeyValue(
                                                                 ConfigurationProvider.GetKey((RhetosAppOptions o) => o.RhetosHostFolder),
                                                                 Path.GetDirectoryName(rhetosHostAssemblyPath))); // Override the RhetosHostFolder to make sure it is set to the original host folder location, not a shadow copy (for applications such as LINQPad).

                    configureRhetosHost?.Invoke(rhetosHostBuilder);
                });
            });

            if (configureServices != null)
            {
                hostBuilder.ConfigureServices(configureServices);
            }

            return(hostBuilder.Build().Services);
        }