System.IServiceProvider.GetService()

Here are the examples of the csharp api System.IServiceProvider.GetService() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

177 Examples 7

19 Source : GmicConfigDialog.cs
with GNU General Public License v3.0
from 0xC0000054

private void ShowErrorMessage(Exception exception)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<Exception>((Exception ex) => Services.GetService<IExceptionDialogService>().ShowErrorDialog(this, ex.Message, ex)),
                       exception);
            }
            else
            {
                Services.GetService<IExceptionDialogService>().ShowErrorDialog(this, exception.Message, exception);
            }
        }

19 Source : GmicConfigDialog.cs
with GNU General Public License v3.0
from 0xC0000054

private void ShowErrorMessage(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>((string error) => Services.GetService<IExceptionDialogService>().ShowErrorDialog(this, error, string.Empty)),
                       message);
            }
            else
            {
                Services.GetService<IExceptionDialogService>().ShowErrorDialog(this, message, string.Empty);
            }
        }

19 Source : GmicEffect.cs
with GNU General Public License v3.0
from 0xC0000054

protected override void OnSetRenderInfo(EffectConfigToken parameters, RenderArgs dstArgs, RenderArgs srcArgs)
        {
            if (repeatEffect)
            {
                GmicConfigToken token = (GmicConfigToken)parameters;

                if (token.Surface != null)
                {
                    token.Surface.Dispose();
                    token.Surface = null;
                }

                if (File.Exists(GmicConfigDialog.GmicPath))
                {
                    try
                    {
                        using (GmicPipeServer server = new GmicPipeServer())
                        {
                            List<GmicLayer> layers = new List<GmicLayer>();

                            Surface clipboardSurface = null;
                            try
                            {
                                // Some G'MIC filters require the image to have more than one layer.
                                // Because use Paint.NET does not currently support Effect plug-ins accessing
                                // other layers in the doreplacedent, allowing the user to place the second layer on
                                // the clipboard is supported as a workaround.

                                clipboardSurface = Services.GetService<IClipboardService>().TryGetSurface();

                                if (clipboardSurface != null)
                                {
                                    layers.Add(new GmicLayer(clipboardSurface, true));
                                    clipboardSurface = null;
                                }
                            }
                            finally
                            {
                                if (clipboardSurface != null)
                                {
                                    clipboardSurface.Dispose();
                                }
                            }

                            layers.Add(new GmicLayer(EnvironmentParameters.SourceSurface, false));

                            server.AddLayers(layers);

                            server.Start();

                            string arguments = string.Format(CultureInfo.InvariantCulture, ".PDN {0} reapply", server.FullPipeName);

                            using (Process process = new Process())
                            {
                                process.StartInfo = new ProcessStartInfo(GmicConfigDialog.GmicPath, arguments);

                                process.Start();
                                process.WaitForExit();

                                if (process.ExitCode == GmicExitCode.Ok)
                                {
                                    OutputImageState state = server.OutputImageState;

                                    if (state.Error != null)
                                    {
                                        ShowErrorMessage(state.Error);
                                    }
                                    else
                                    {
                                        IReadOnlyList<Surface> outputImages = state.OutputImages;

                                        if (outputImages.Count > 1)
                                        {
                                            using (PlatformFolderBrowserDialog folderBrowserDialog = new PlatformFolderBrowserDialog())
                                            {
                                                folderBrowserDialog.ClreplacedicFolderBrowserDescription = Resources.ClreplacedicFolderBrowserDescription;
                                                folderBrowserDialog.VistaFolderBrowserreplacedle = Resources.VistaFolderBrowserreplacedle;

                                                if (!string.IsNullOrWhiteSpace(token.OutputFolder))
                                                {
                                                    folderBrowserDialog.SelectedPath = token.OutputFolder;
                                                }

                                                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                                                {
                                                    string outputFolder = folderBrowserDialog.SelectedPath;

                                                    try
                                                    {
                                                        OutputImageUtil.SaveAllToFolder(outputImages, outputFolder);
                                                    }
                                                    catch (ArgumentException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (ExternalException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (IOException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (SecurityException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (UnauthorizedAccessException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            Surface output = outputImages[0];

                                            if (output.Width == srcArgs.Surface.Width && output.Height == srcArgs.Surface.Height)
                                            {
                                                token.Surface = output.Clone();
                                            }
                                            else
                                            {
                                                // Place the full image on the clipboard when the size does not match the Paint.NET layer
                                                // and prompt the user to save it.
                                                // The resized image will not be copied to the Paint.NET canvas.
                                                Services.GetService<IClipboardService>().SetImage(output);

                                                using (PlatformFileSaveDialog resizedImageSaveDialog = new PlatformFileSaveDialog())
                                                {
                                                    resizedImageSaveDialog.Filter = Resources.ResizedImageSaveDialogFilter;
                                                    resizedImageSaveDialog.replacedle = Resources.ResizedImageSaveDialogreplacedle;
                                                    resizedImageSaveDialog.FileName = DateTime.Now.ToString("yyyyMMdd-THHmmss") + ".png";
                                                    if (resizedImageSaveDialog.ShowDialog() == DialogResult.OK)
                                                    {
                                                        string resizedImagePath = resizedImageSaveDialog.FileName;
                                                        try
                                                        {
                                                            using (Bitmap bitmap = output.CreateAliasedBitmap())
                                                            {
                                                                bitmap.Save(resizedImagePath, System.Drawing.Imaging.ImageFormat.Png);
                                                            }
                                                        }
                                                        catch (ArgumentException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (ExternalException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (IOException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (SecurityException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (UnauthorizedAccessException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    switch (process.ExitCode)
                                    {
                                        case GmicExitCode.ImageTooLargeForX86:
                                            ShowErrorMessage(Resources.ImageTooLargeForX86);
                                            break;
                                    }
                                }
                            }
                        }
                    }
                    catch (ArgumentException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                    catch (ExternalException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                    catch (IOException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                }
                else
                {
                    ShowErrorMessage(Resources.GmicNotFound);
                }
            }

            base.OnSetRenderInfo(parameters, dstArgs, srcArgs);
        }

19 Source : DdsFile.cs
with MIT License
from 0xC0000054

public static void Save(
            IServiceProvider services,
            Doreplacedent input,
            Stream output,
            DdsFileFormat format,
            DdsErrorMetric errorMetric,
            BC7CompressionSpeed compressionSpeed,
            bool cubeMap,
            bool generateMipmaps,
            ResamplingAlgorithm sampling,
            Surface scratchSurface,
            ProgressEventHandler progressCallback)
        {
            scratchSurface.Clear();
            input.CreateRenderer().Render(scratchSurface);

            int width = scratchSurface.Width;
            int height = scratchSurface.Height;
            int arraySize = 1;
            Size? cubeMapFaceSize = null;

            if (cubeMap && IsCrossedCubeMapSize(scratchSurface))
            {
                if (width > height)
                {
                    width /= 4;
                    height /= 3;
                }
                else
                {
                    width /= 3;
                    height /= 4;
                }
                arraySize = 6;
                cubeMapFaceSize = new Size(width, height);
            }

            int mipLevels = generateMipmaps ? GetMipCount(width, height) : 1;
            bool enableHardwareAcceleration = (bool)services.GetService<ISettingsService>().GetSetting(AppSettingPaths.UI.EnableHardwareAcceleration).Value;

            using (TextureCollection textures = GetTextures(scratchSurface, cubeMapFaceSize, mipLevels, sampling))
            {
                if (format == DdsFileFormat.R8G8B8X8 || format == DdsFileFormat.B8G8R8)
                {
                    new DX9DdsWriter(width, height, arraySize, mipLevels, format).Save(textures, output, progressCallback);
                }
                else
                {
                    DdsProgressCallback ddsProgress = null;
                    if (progressCallback != null)
                    {
                        ddsProgress = (UIntPtr done, UIntPtr total) =>
                        {
                            double progress = (double)done.ToUInt64() / (double)total.ToUInt64();
                            try
                            {
                                progressCallback(null, new ProgressEventArgs(progress * 100.0, true));
                                return true;
                            }
                            catch (OperationCanceledException)
                            {
                                return false;
                            }
                        };
                    }

                    DDSSaveInfo info = new DDSSaveInfo
                    {
                        width = width,
                        height = height,
                        arraySize = arraySize,
                        mipLevels = mipLevels,
                        format = format,
                        errorMetric = errorMetric,
                        compressionSpeed = compressionSpeed,
                        cubeMap = cubeMapFaceSize.HasValue,
                        enableHardwareAcceleration = enableHardwareAcceleration
                    };

                    DdsNative.Save(info, textures, output, ddsProgress);
                }
            }
        }

19 Source : GmicConfigDialog.cs
with GNU General Public License v3.0
from 0xC0000054

private void GmicThread()
        {
            DialogResult result = DialogResult.Cancel;

            try
            {
                List<GmicLayer> layers = new List<GmicLayer>();

                Surface clipboardSurface = null;
                try
                {
                    // Some G'MIC filters require the image to have more than one layer.
                    // Because use Paint.NET does not currently support Effect plug-ins accessing
                    // other layers in the doreplacedent, allowing the user to place the second layer on
                    // the clipboard is supported as a workaround.

                    clipboardSurface = Services.GetService<IClipboardService>().TryGetSurface();

                    if (clipboardSurface != null)
                    {
                        layers.Add(new GmicLayer(clipboardSurface, true));
                        clipboardSurface = null;
                    }
                }
                finally
                {
                    if (clipboardSurface != null)
                    {
                        clipboardSurface.Dispose();
                    }
                }

                layers.Add(new GmicLayer(EnvironmentParameters.SourceSurface, false));

                server.AddLayers(layers);

                server.Start();

                string arguments = string.Format(CultureInfo.InvariantCulture, ".PDN {0}", server.FullPipeName);

                using (Process process = new Process())
                {
                    process.StartInfo = new ProcessStartInfo(GmicPath, arguments);

                    process.Start();
                    process.WaitForExit();

                    if (process.ExitCode == GmicExitCode.Ok)
                    {
                        result = DialogResult.OK;
                    }
                    else
                    {
                        surface?.Dispose();
                        surface = null;

                        switch (process.ExitCode)
                        {
                            case GmicExitCode.ImageTooLargeForX86:
                                ShowErrorMessage(Resources.ImageTooLargeForX86);
                                break;
                        }
                    }
                }
            }
            catch (ArgumentException ex)
            {
                ShowErrorMessage(ex);
            }
            catch (ExternalException ex)
            {
                ShowErrorMessage(ex);
            }
            catch (IOException ex)
            {
                ShowErrorMessage(ex);
            }
            catch (UnauthorizedAccessException ex)
            {
                ShowErrorMessage(ex);
            }

            BeginInvoke(new Action<DialogResult>(GmicThreadFinished), result);
        }

19 Source : GmicConfigDialog.cs
with GNU General Public License v3.0
from 0xC0000054

private DialogResult ProcessOutputImages()
        {
            DialogResult result = DialogResult.Cancel;

            OutputImageState state = server.OutputImageState;

            if (state.Error != null)
            {
                ShowErrorMessage(state.Error);
            }
            else
            {
                IReadOnlyList<Surface> outputImages = state.OutputImages;

                if (outputImages.Count > 1)
                {
                    if (!string.IsNullOrWhiteSpace(outputFolder))
                    {
                        folderBrowserDialog.SelectedPath = outputFolder;
                    }

                    if (folderBrowserDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        outputFolder = folderBrowserDialog.SelectedPath;

                        try
                        {
                            OutputImageUtil.SaveAllToFolder(outputImages, outputFolder);

                            surface?.Dispose();
                            surface = null;
                            result = DialogResult.OK;
                        }
                        catch (ArgumentException ex)
                        {
                            ShowErrorMessage(ex);
                        }
                        catch (ExternalException ex)
                        {
                            ShowErrorMessage(ex);
                        }
                        catch (IOException ex)
                        {
                            ShowErrorMessage(ex);
                        }
                        catch (SecurityException ex)
                        {
                            ShowErrorMessage(ex);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            ShowErrorMessage(ex);
                        }
                    }
                }
                else
                {
                    Surface output = outputImages[0];

                    if (output.Size == EnvironmentParameters.SourceSurface.Size)
                    {
                        if (surface == null)
                        {
                            surface = new Surface(EnvironmentParameters.SourceSurface.Width, EnvironmentParameters.SourceSurface.Height);
                        }

                        surface.CopySurface(output);
                        result = DialogResult.OK;
                    }
                    else
                    {
                        if (surface != null)
                        {
                            surface.Dispose();
                            surface = null;
                        }

                        // Place the full image on the clipboard when the size does not match the Paint.NET layer
                        // and prompt the user to save it.
                        // The resized image will not be copied to the Paint.NET canvas.
                        Services.GetService<IClipboardService>().SetImage(output);

                        resizedImageSaveDialog.FileName = DateTime.Now.ToString("yyyyMMdd-THHmmss") + ".png";
                        if (resizedImageSaveDialog.ShowDialog(this) == DialogResult.OK)
                        {
                            string resizedImagePath = resizedImageSaveDialog.FileName;
                            try
                            {
                                using (Bitmap bitmap = output.CreateAliasedBitmap())
                                {
                                    bitmap.Save(resizedImagePath, System.Drawing.Imaging.ImageFormat.Png);
                                }

                                result = DialogResult.OK;
                            }
                            catch (ArgumentException ex)
                            {
                                ShowErrorMessage(ex);
                            }
                            catch (ExternalException ex)
                            {
                                ShowErrorMessage(ex);
                            }
                            catch (IOException ex)
                            {
                                ShowErrorMessage(ex);
                            }
                            catch (SecurityException ex)
                            {
                                ShowErrorMessage(ex);
                            }
                            catch (UnauthorizedAccessException ex)
                            {
                                ShowErrorMessage(ex);
                            }
                        }
                    }
                }

                FinishTokenUpdate();
            }

            return result;
        }

19 Source : GmicEffect.cs
with GNU General Public License v3.0
from 0xC0000054

private void ShowErrorMessage(Exception exception)
        {
            Services.GetService<IExceptionDialogService>().ShowErrorDialog(null, exception.Message, exception);
        }

19 Source : GmicEffect.cs
with GNU General Public License v3.0
from 0xC0000054

private void ShowErrorMessage(string message)
        {
            Services.GetService<IExceptionDialogService>().ShowErrorDialog(null, message, string.Empty);
        }

19 Source : ServiceProviderExtensions.cs
with GNU General Public License v3.0
from Artentus

public static T? GetFirstParent<T>(this IServiceProvider ctx) where T : clreplaced
            => ctx.GetService<IAvaloniaXamlIlParentStackProvider>()?.Parents.OfType<T>().FirstOrDefault();

19 Source : ServiceProviderExtensions.cs
with GNU General Public License v3.0
from Artentus

public static Type? ResolveType(this IServiceProvider ctx, string namespacePrefix, string type)
        {
            var tr = ctx.GetService<IXamlTypeResolver>();
            string name = string.IsNullOrEmpty(namespacePrefix) ? type : $"{namespacePrefix}:{type}";
            return tr?.Resolve(name);
        }

19 Source : WebApp.cs
with Apache License 2.0
from aspnet

private static IDisposable StartImplementation(IServiceProvider services, StartOptions options, Action<IAppBuilder> startup)
        {
            if (services == null)
            {
                throw new ArgumentNullException("services");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (startup == null)
            {
                throw new ArgumentNullException("startup");
            }

            if (string.IsNullOrWhiteSpace(options.AppStartup))
            {
                // Populate AppStartup for use in host.AppName
                options.AppStartup = startup.Method.ReflectedType.FullName;
            }

            var engine = services.GetService<IHostingEngine>();
            if (engine == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    Resources.Exception_FailedToResolveService, "IHostingEngine"));
            }
            var context = new StartContext(options);
            context.Startup = startup;
            return engine.Start(context);
        }

19 Source : TestServer.cs
with Apache License 2.0
from aspnet

protected void Configure<TStartup>(StartOptions options)
        {
            // Compare with WebApp.StartImplementation
            options = options ?? new StartOptions();
            options.AppStartup = typeof(TStartup).replacedemblyQualifiedName;

            var testServerFactory = new TestServerFactory();
            IServiceProvider services = ServicesFactory.Create();
            var engine = services.GetService<IHostingEngine>();
            var context = new StartContext(options);
            context.ServerFactory = new ServerFactoryAdapter(testServerFactory);
            _started = engine.Start(context);
            _next = testServerFactory.Invoke;
        }

19 Source : DomainHostingStarterAgent.cs
with Apache License 2.0
from aspnet

[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersreplacedtatic", Justification = "Non-static needed for calling across AppDomain")]
        public virtual void Start(StartOptions options)
        {
            var context = new StartContext(options);

            IServiceProvider services = ServicesFactory.Create(context.Options.Settings);

            var engine = services.GetService<IHostingEngine>();

            _runningApp = engine.Start(context);

            _lease = (ILease)RemotingServices.GetLifetimeService(this);
            _lease.Register(this);
        }

19 Source : WebApp.cs
with Apache License 2.0
from aspnet

private static IDisposable StartImplementation(IServiceProvider services, StartOptions options)
        {
            if (services == null)
            {
                throw new ArgumentNullException("services");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            var starter = services.GetService<IHostingStarter>();
            if (starter == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                    Resources.Exception_FailedToResolveService, "IHostingStarter"));
            }
            return starter.Start(options);
        }

19 Source : TestServer.cs
with Apache License 2.0
from aspnet

protected void Configure(Action<IAppBuilder> startup, StartOptions options)
        {
            // Compare with WebApp.StartImplementation
            if (startup == null)
            {
                throw new ArgumentNullException("startup");
            }

            options = options ?? new StartOptions();
            if (string.IsNullOrWhiteSpace(options.AppStartup))
            {
                // Populate AppStartup for use in host.AppName
                options.AppStartup = startup.Method.ReflectedType.FullName;
            }

            var testServerFactory = new TestServerFactory();
            IServiceProvider services = ServicesFactory.Create();
            var engine = services.GetService<IHostingEngine>();
            var context = new StartContext(options);
            context.ServerFactory = new ServerFactoryAdapter(testServerFactory);
            context.Startup = startup;
            _started = engine.Start(context);
            _next = testServerFactory.Invoke;
        }

19 Source : Program.cs
with Apache License 2.0
from aspnet

public static void RunServer(StartOptions options)
        {
            if (options == null)
            {
                return;
            }

            string boot;
            if (!options.Settings.TryGetValue("boot", out boot)
                || string.IsNullOrWhiteSpace(boot))
            {
                options.Settings["boot"] = "Domain";
            }

            ResolvereplacedembliesFromDirectory(
                Path.Combine(Directory.GetCurrentDirectory(), "bin"));

            WriteLine("Starting with " + GetDisplayUrl(options));

            IServiceProvider services = ServicesFactory.Create();
            var starter = services.GetService<IHostingStarter>();
            IDisposable server = starter.Start(options);

            WriteLine("Started successfully");

            WriteLine("Press Enter to exit");
            Console.ReadLine();

            WriteLine("Terminating.");

            server.Dispose();
        }

19 Source : HostingEngineTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void PropertiesShouldHaveExpectedKeysFromHost()
        {
            var serverFactory = new ServerFactoryAlpha();
            var startInfo = new StartContext(new StartOptions());
            startInfo.ServerFactory = new ServerFactoryAdapter(serverFactory);
            startInfo.App = new AppFunc(env => Task.FromResult(0));

            var engine = ServicesFactory.Create().GetService<IHostingEngine>();
            serverFactory.InitializeCalled.ShouldBe(false);
            serverFactory.CreateCalled.ShouldBe(false);
            IDisposable server = engine.Start(startInfo);

            serverFactory.InitializeProperties.ShouldContainKey("host.TraceOutput");
            serverFactory.InitializeProperties.ShouldContainKey("host.Addresses");

            serverFactory.InitializeProperties["host.TraceOutput"].ShouldBeTypeOf<TextWriter>();
            serverFactory.InitializeProperties["host.Addresses"].ShouldBeTypeOf<IList<IDictionary<string, object>>>();

            server.Dispose();
        }

19 Source : HostingEngineTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void MultipleUrlsSpecified()
        {
            var startOptions = new StartOptions();
            startOptions.Urls.Add("beta://localhost:3333");
            startOptions.Urls.Add("delta://foo/");
            startOptions.Urls.Add("gama://*:4444/");
            startOptions.Port = 1111; // Ignored because of Url(s)

            var serverFactory = new ServerFactoryAlpha();
            var startInfo = new StartContext(startOptions);
            startInfo.ServerFactory = new ServerFactoryAdapter(serverFactory);
            startInfo.App = new AppFunc(env => Task.FromResult(0));

            var engine = ServicesFactory.Create().GetService<IHostingEngine>();
            serverFactory.InitializeCalled.ShouldBe(false);
            serverFactory.CreateCalled.ShouldBe(false);
            IDisposable server = engine.Start(startInfo);

            serverFactory.InitializeProperties["host.Addresses"].ShouldBeTypeOf<IList<IDictionary<string, object>>>();

            var addresses = (IList<IDictionary<string, object>>)serverFactory.InitializeProperties["host.Addresses"];
            replacedert.Equal(3, addresses.Count);

            var expectedAddresses = new[]
            {
                new[] { "beta", "localhost", "3333", string.Empty },
                new[] { "delta", "foo", string.Empty, "/" },
                new[] { "gama", "*", "4444", "/" },
            };

            for (int i = 0; i < addresses.Count; i++)
            {
                IDictionary<string, object> addressDictionary = addresses[i];
                string[] expectedValues = expectedAddresses[i];
                replacedert.Equal(expectedValues.Length, addressDictionary.Count);
                replacedert.Equal(expectedValues[0], (string)addressDictionary["scheme"]);
                replacedert.Equal(expectedValues[1], (string)addressDictionary["host"]);
                replacedert.Equal(expectedValues[2], (string)addressDictionary["port"]);
                replacedert.Equal(expectedValues[3], (string)addressDictionary["path"]);
            }

            server.Dispose();
        }

19 Source : HostingEngineTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void CreateShouldBeProvidedWithAdaptedAppIfNeeded()
        {
            var serverFactoryBeta = new ServerFactoryBeta();
            var startInfo = new StartContext(new StartOptions());
            startInfo.ServerFactory = new ServerFactoryAdapter(serverFactoryBeta);
            startInfo.App = new AppFunc(env => Task.FromResult(0));

            var engine = ServicesFactory.Create().GetService<IHostingEngine>();
            serverFactoryBeta.CreateCalled.ShouldBe(false);
            IDisposable server = engine.Start(startInfo);
            serverFactoryBeta.CreateCalled.ShouldBe(true);
            server.Dispose();
        }

19 Source : HostingEngineTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void InitializeAndCreateShouldBeCalledWithProperties()
        {
            var serverFactoryAlpha = new ServerFactoryAlpha();
            var startInfo = new StartContext(new StartOptions());
            startInfo.ServerFactory = new ServerFactoryAdapter(serverFactoryAlpha);
            startInfo.App = new AppFunc(env => Task.FromResult(0));

            var engine = ServicesFactory.Create().GetService<IHostingEngine>();

            serverFactoryAlpha.InitializeCalled.ShouldBe(false);
            serverFactoryAlpha.CreateCalled.ShouldBe(false);
            IDisposable server = engine.Start(startInfo);

            serverFactoryAlpha.InitializeCalled.ShouldBe(true);
            serverFactoryAlpha.CreateCalled.ShouldBe(true);
            serverFactoryAlpha.InitializeProperties.ShouldBeSameAs(serverFactoryAlpha.CreateProperties);
            server.Dispose();
        }

19 Source : Startup.cs
with MIT License
from Azure-Samples

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                var initTask = serviceScope.ServiceProvider.GetService<IMDbRepository>().InitializeDatabase();
                initTask.Wait();
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            
            app.UseStaticFiles();
            //app.UseStaticFiles(new StaticFileOptions()
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"node_modules")),
            //    RequestPath = new PathString("/node_modules")
            //});

            app.UseCookieAuthentication();

            app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
            {
                ClientId = Configuration["Authentication:AzureAd:ClientId"],
                Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
                CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"]
            });

            //app.UseMiddleware(typeof(ExceptionHandlingMiddleware));

            app.UseMvc(routes =>
            {
                //routes.MapRoute(
                //    name: "default",
                //    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
                    name: "account-routes",
                    template: "account/{action=Index}/{id?}",
                    defaults: new { controller = "Account" }
                );
                routes.MapRoute(
                    name: "spa-fallback",
                    template: "{*url}",
                    defaults: new { controller = "Home", action = "Index" }
                );
            });


            app.UseNodeModules(env);

            //TODO: ensure DocDb collections existence
            
        }

19 Source : OwinServiceProvider.cs
with GNU General Public License v3.0
from bonarr

public IDisposable CreateApp(List<string> urls)
        {
            var services = CreateServiceFactory();
            var engine = services.GetService<IHostingEngine>();

            var options = new StartOptions()
            {
                ServerFactory = "Microsoft.Owin.Host.HttpListener"
            };

            urls.ForEach(options.Urls.Add);

            var context = new StartContext(options) { Startup = BuildApp };


            try
            {
                return engine.Start(context);
            }
            catch (TargetInvocationException ex)
            {
                if (ex.InnerException == null)
                {
                    throw;
                }

                if (ex.InnerException is HttpListenerException)
                {
                    throw new PortInUseException("Port {0} is already in use, please ensure NzbDrone is not already running.", ex, _configFileProvider.Port);
                }

                throw ex.InnerException;
            }
        }

19 Source : Operator.cs
with MIT License
from Coldairarrow

public void WriteUserLog(UserLogType userLogType, string msg)
        {
            var log = new Base_UserLog
            {
                Id = IdHelper.GetId(),
                CreateTime = DateTime.Now,
                CreatorId = UserId,
                CreatorRealName = Property.RealName,
                LogContent = msg,
                LogType = userLogType.ToString()
            };

            Task.Factory.StartNew(async () =>
            {
                using (var scop = _serviceProvider.CreateScope())
                {
                    var db = scop.ServiceProvider.GetService<IDbAccessor>();
                    await db.InsertAsync(log);
                }
            }, TaskCreationOptions.LongRunning);
        }

19 Source : ShardingDbAccessorTest.cs
with Apache License 2.0
from Coldairarrow

[TestMethod]
        public void RunTransaction_isolationLevel()
        {
            var db1 = ServiceProvider.GetService<IShardingDbAccessor>();
            var db2 = ServiceProvider.CreateScope().ServiceProvider.GetService<IShardingDbAccessor>();
            db1.Insert(_newData);

            var updateData = _newData.DeepClone();
            Task db2Task = new Task(() =>
            {
                updateData.UserName = Guid.NewGuid().ToString();
                db2.Update(updateData);
            });

            var res = db1.RunTransaction(() =>
            {
                //db1读=>db2写(阻塞)=>db1读=>db1提交
                var db1Data_1 = db1.GetIShardingQueryable<Base_UnitTest>().Where(x => x.Id == _newData.Id).FirstOrDefault();

                db2Task.Start();

                var db1Data_2 = db1.GetIShardingQueryable<Base_UnitTest>().Where(x => x.Id == _newData.Id).FirstOrDefault();
                replacedert.AreEqual(db1Data_1.ToJson(), db1Data_2.ToJson());
            });
            db2Task.Wait();
            var db1Data_3 = db1.GetIShardingQueryable<Base_UnitTest>().Where(x => x.Id == _newData.Id).FirstOrDefault();
            replacedert.AreEqual(updateData.ToJson(), db1Data_3.ToJson());
        }

19 Source : DbAccessorTest.cs
with Apache License 2.0
from Coldairarrow

[TestMethod]
        public void RunTransaction_isolationLevel()
        {
            var db1 = ServiceProvider.GetService<ISQLiteDb1>();
            var db2 = ServiceScopeFactory.CreateScope().ServiceProvider.GetService<ISQLiteDb1>();

            db1.Insert(_newData);

            var updateData = _newData.DeepClone();
            Task db2Task = new Task(() =>
            {
                updateData.UserName = Guid.NewGuid().ToString();
                db2.Update(updateData);
            });

            var res = db1.RunTransaction(() =>
            {
                //db1读=>db2写(阻塞)=>db1读=>db1提交
                var db1Data_1 = db1.GetIQueryable<Base_UnitTest>().Where(x => x.Id == _newData.Id).FirstOrDefault();

                db2Task.Start();

                var db1Data_2 = db1.GetIQueryable<Base_UnitTest>().Where(x => x.Id == _newData.Id).FirstOrDefault();
                replacedert.AreEqual(db1Data_1.ToJson(), db1Data_2.ToJson());
            });
            db2Task.Wait();
            var db1Data_3 = db1.GetIQueryable<Base_UnitTest>().Where(x => x.Id == _newData.Id).FirstOrDefault();
            replacedert.AreEqual(updateData.ToJson(), db1Data_3.ToJson());
        }

19 Source : DbAccessorTest.cs
with Apache License 2.0
from Coldairarrow

[TestMethod]
        public void Dispose()
        {
            using (var scop = RootServiceProvider.CreateScope())
            {
                scop.ServiceProvider.GetService<IDbAccessor>().Dispose();
                scop.ServiceProvider.GetService<ICustomDbAccessor>().Dispose();
            }
        }

19 Source : ServiceProviderExtensions.cs
with MIT License
from connellw

public static IEnumerable<T> GetServices<T>(this IServiceProvider provider)
        {
            return provider.GetService<IEnumerable<T>>()
                   ?? Enumerable.Empty<T>();
        }

19 Source : ServiceProviderExtensions.cs
with MIT License
from connellw

public static IRequestServiceProvider GetRequestServiceProvider(this IServiceProvider serviceProvider)
        {
            return serviceProvider.GetService<IRequestServiceProvider>() ??
                   throw new NotImplementedException("Request service provider is not implemented.");
        }

19 Source : GenericDesigner.cs
with MIT License
from dahall

private T GetService<T>() where T : clreplaced => ((IServiceProvider)this).GetService<T>();

19 Source : Extensions.cs
with MIT License
from DevZest

private static IVsEditorAdaptersFactoryService GetEditorAdaptersFactoryService(this IServiceProvider serviceProvider)
        {
            IComponentModel componentModel = serviceProvider.GetService<IComponentModel, SComponentModel>();
            return componentModel.GetService<IVsEditorAdaptersFactoryService>();
        }

19 Source : Extensions.cs
with MIT License
from DevZest

private static IVsTextView GetActiveVsTextView(this IServiceProvider serviceProvider)
        {
            IVsTextManager textManager = serviceProvider.GetService<IVsTextManager, SVsTextManager>();
            if (textManager == null)
                return null;
            textManager.GetActiveView(0, null, out var result);
            return result;
        }

19 Source : Extensions.cs
with MIT License
from DevZest

public static EnvDTE.DTE GetDTE(this IServiceProvider serviceProvider)
        {
            return serviceProvider.GetService<EnvDTE.DTE, EnvDTE.DTE>();
        }

19 Source : DelegatedStatelessService.cs
with MIT License
from dotnet

private async Task RunAsyncLoop(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                using (IServiceScope scope = _container.CreateScope())
                {
                    var impl = scope.ServiceProvider.GetService<TServiceImplementation>();

                    var shouldWaitFor = await impl.RunAsync(cancellationToken);

                    if (shouldWaitFor.Equals(TimeSpan.MaxValue))
                    {
                        return;
                    }

                    await Task.Delay(shouldWaitFor, cancellationToken);
                }
            }
        }

19 Source : ServiceHost.AI.cs
with MIT License
from dotnet

private static FabricTelemetryInitializer ConfigureFabricTelemetryInitializer(IServiceProvider provider)
        {
            var props = new Dictionary<string, string>();
            var serviceContext = provider.GetService<ServiceContext>();
            if (serviceContext != null)
            {
                props["ServiceFabric.ServiceName"] = serviceContext.ServiceName.ToString();
                props["cloud_RoleName"] = serviceContext.ServiceName.ToString();
                props["ServiceFabric.ServiceTypeName"] = serviceContext.ServiceTypeName;
                props["ServiceFabric.ParreplacedionId"] = serviceContext.ParreplacedionId.ToString();
                props["ServiceFabric.ApplicationName"] = serviceContext.CodePackageActivationContext.ApplicationName;
                props["ServiceFabric.ApplicationTypeName"] =
                    serviceContext.CodePackageActivationContext.ApplicationTypeName;
                props["ServiceFabric.NodeName"] = serviceContext.NodeContext.NodeName;
                if (serviceContext is StatelessServiceContext)
                {
                    props["ServiceFabric.InstanceId"] =
                        serviceContext.ReplicaOrInstanceId.ToString(CultureInfo.InvariantCulture);
                }

                if (serviceContext is StatefulServiceContext)
                {
                    props["ServiceFabric.ReplicaId"] =
                        serviceContext.ReplicaOrInstanceId.ToString(CultureInfo.InvariantCulture);
                }
            }

            return new FabricTelemetryInitializer(props);
        }

19 Source : DependencyInjectedConsoleApp.cs
with MIT License
from dotnet

public static async Task RunCommandAsync(
            IServiceProvider provider,
            IEnumerable<string> args)
        {
            Command currentCommand;

            void ShowHelp(List<OptionSet> options, IReadOnlyDictionary<string, Type> commands)
            {
                var console = provider.GetRequiredService<IConsoleBackend>();
                console.Out.WriteLine(currentCommand.GetDetailedHelpText());
                console.Out.WriteLine();
                WriteGeneralUsage(console.Out, options, commands);
            }

            var commandTree = new List<Command>();
            var allOptions = new List<OptionSet>();
            var globalCommand = ActivatorUtilities.CreateInstance<GlobalCommand>(provider);
            var commandNames = new List<string>();
            currentCommand = globalCommand;

            var logger = provider.GetRequiredService<ILogger<DependencyInjectedConsoleApp>>();

            while (true)
            {
                // There are some unused arguments, and we have a child command to execute
                var commandOptions = provider.GetService<ICommandOptions>() as CommandOptions;
                commandOptions?.RegisterOptions(currentCommand);
                commandTree.Add(currentCommand);
                IReadOnlyDictionary<string, Type> commands = provider.GetRequiredService<ICommandRegistry>()
                    .GetValidCommandAtScope(currentCommand.GetType());
                OptionSet optionSet = currentCommand.GetOptions();
                allOptions.Add(optionSet);
                List<string> unused = optionSet.Parse(args);
                unused = currentCommand.HandlePositionalArguments(unused);

                if (unused.Count > 0 && string.Equals(unused[0], "help", StringComparison.OrdinalIgnoreCase))
                {
                    // Help was requested!
                    ShowHelp(allOptions, commands);
                    return;
                }

                if (unused.Count == 0)
                {
                    if (globalCommand.Help)
                    {
                        // Help was requested!
                        ShowHelp(allOptions, commands);
                        return;
                    }

                    // All arguments used, success!

                    foreach (Command c in commandTree)
                    {
                        if (!c.AreRequiredOptionsSet())
                        {
                            var console = provider.GetRequiredService<IConsoleBackend>();
                            console.SetColor(ConsoleColor.Red);
                            await console.Error.WriteLineAsync("Required parameters not set");
                            console.ResetColor();
                            WriteGeneralUsage(console.Error, allOptions, ImmutableDictionary<string, Type>.Empty);
                            throw new FailWithExitCodeException(ExitCodes.RequiredParameter);
                        }
                    }

                    Activity activity = new Activity($"EXEC {string.Join(" ", commandNames)}").SetIdFormat(ActivityIdFormat.Hierarchical).Start();
                    try
                    {
                        // Set up cancellation with CTRL-C, so we can attempt to "cancel" cleanly
                        var ctrlC = new CancellationTokenSource();
                        Console.CancelKeyPress += (sender, eventArgs) =>
                        {
                            if (ctrlC.IsCancellationRequested)
                            {
                                // We are already cancelling, they double cancelled!
                                logger.LogError("Force cancellation requested");
                                Environment.Exit(ExitCodes.Break);
                                return;
                            }

                            ctrlC.Cancel();
                            Console.Error.WriteLine(
                                "Ctrl-C pressed, cancelling operation... (Press again to force cancellation)"
                            );
                            logger.LogWarning("Cancellation requested");
                            eventArgs.Cancel = true;
                        };

                        Task runTask = currentCommand.RunAsync(ctrlC.Token);
                        if (runTask == null)
                        {
                            // No implementation, we need a subcommand, dump usage
                            var console = provider.GetRequiredService<IConsoleBackend>();
                            WriteGeneralUsage(console.Error, allOptions, commands);
                            throw new FailWithExitCodeException(ExitCodes.MissingCommand);
                        }

                        try
                        {
                            await runTask;
                            return;
                        }
                        catch (FailWithExitCodeException)
                        {
                            throw;
                        }
                        catch (Exception e)
                        {
                            logger.LogError(e, "Unhandled exception");
                            var console = provider.GetRequiredService<IConsole>();
                            console.WriteError("Unhandled exception: " + e.Message);
                            throw new FailWithExitCodeException(ExitCodes.UnhandledException);
                        }
                    }
                    finally
                    {
                        activity.Stop();
                    }
                }

                var commandToExecute = unused[0];
                unused.RemoveAt(0);

                if (string.Equals(commandToExecute, "help", StringComparison.OrdinalIgnoreCase))
                {
                    provider.GetService<ICommandOptions>().GetOptions<GlobalCommand>().Help = true;
                }

                if (!commands.TryGetValue(commandToExecute, out Type childCommandType))
                {
                    if (provider.GetService<ICommandOptions>().GetOptions<GlobalCommand>().Help)
                    {
                        // We are out of commands, and help was requested, so let's do the most specific help possible
                        ShowHelp(allOptions, commands);
                        return;
                    }

                    // No help, and we didn't understand what they asked... error!
                    var console = provider.GetRequiredService<IConsoleBackend>();
                    console.SetColor(ConsoleColor.Red);
                    await console.Error.WriteLineAsync($"Unrecognized argument/command '{commandToExecute}'");
                    console.ResetColor();
                    WriteGeneralUsage(console.Error, allOptions, commands);
                    throw new FailWithExitCodeException(ExitCodes.UnknownArgument);
                }

                commandNames.Add(commandToExecute);
                args = unused;
                currentCommand = (Command)ActivatorUtilities.CreateInstance(provider, childCommandType);
            }
        }

19 Source : ScopeValidationBenchmark.cs
with MIT License
from dotnet

[Benchmark(Baseline = true)]
        public A Transient() => _transientSp.GetService<A>();

19 Source : ScopeValidationBenchmark.cs
with MIT License
from dotnet

[Benchmark]
        public A TransientWithScopeValidation() => _transientSpScopeValidation.GetService<A>();

19 Source : TimeToFirstServiceBenchmark.cs
with MIT License
from dotnet

[Benchmark]
        public void Scoped()
        {
            using ServiceProvider provider = _scopedServices.BuildServiceProvider(new ServiceProviderOptions()
            {
#if INTERNAL_DI
                Mode = _mode
#endif
            });
            IServiceScope scopedSp = provider.CreateScope();
            var temp = scopedSp.ServiceProvider.GetService<A>();
            temp.Foo();
        }

19 Source : GetServiceBenchmark.cs
with MIT License
from dotnet

[Benchmark]
        public A Transient() => _transientSp.GetService<A>();

19 Source : GetServiceBenchmark.cs
with MIT License
from dotnet

[Benchmark]
        public A Scoped() => _scopedSp.ServiceProvider.GetService<A>();

19 Source : GetServiceBenchmark.cs
with MIT License
from dotnet

[Benchmark]
        public A Singleton() => _singletonSp.GetService<A>();

19 Source : GetServiceBenchmark.cs
with MIT License
from dotnet

[Benchmark]
        public IServiceScopeFactory ServiceScopeProvider() => _serviceScopeFactoryProvider.GetService<IServiceScopeFactory>();

19 Source : GetServiceBenchmark.cs
with MIT License
from dotnet

[Benchmark]
        public object EmptyEnumerable() =>_emptyEnumerable.GetService<IEnumerable<A>>();

19 Source : IEnumerableGetServiceBenchmark.cs
with MIT License
from dotnet

[Benchmark]
        public object Transient() => _serviceProvider.GetService<IEnumerable<A>>();

19 Source : IEnumerableGetServiceBenchmark.cs
with MIT License
from dotnet

[Benchmark]
        public object Scoped() => _serviceProvider.GetService<IEnumerable<A>>();

19 Source : IEnumerableGetServiceBenchmark.cs
with MIT License
from dotnet

[Benchmark]
        public object Singleton() => _serviceProvider.GetService<IEnumerable<A>>();

19 Source : ServiceExtensions.cs
with MIT License
from dotnet

private static TInterface GetRequiredService<TService, TInterface>(this IServiceProvider provider)
            where TService : clreplaced
            where TInterface : clreplaced
        {
            var service = provider.GetService<TService, TInterface>();

            if (service is null)
            {
                throw new InvalidOperationException(string.Format(SR.General_MissingService, typeof(TInterface).FullName))
                {
                    HelpLink = SR.General_MissingService
                };
            }

            return service;
        }

19 Source : Program.cs
with MIT License
from dotnetcore

static void Main(string[] args)
        {
            Console.WriteLine("Welcome to EasyCaching World!");

            IServiceCollection services = new ServiceCollection();
            services.AddEasyCaching(option =>
            {
                option.UseInMemory("m1");

                //option.UseRedis(config =>
                //{
                //    config.DBConfig = new Redis.RedisDBOptions { Configuration = "localhost" };
                //    config.SerializerName = "json";
                //}, "r1");


                option.UseSQLite(c =>
                {
                    c.DBConfig = new SQLiteDBOptions
                    {
                        FileName = "demo.db",
                        CacheMode = Microsoft.Data.Sqlite.SqliteCacheMode.Default,
                        OpenMode = Microsoft.Data.Sqlite.SqliteOpenMode.Memory,
                    };
                }, "s1");

                //option.WithJson(jsonSerializerSettingsConfigure: x =>
                //{
                //    x.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.None;
                //}, "json");
            });

            IServiceProvider serviceProvider = services.BuildServiceProvider();
            var factory = serviceProvider.GetService<IEasyCachingProviderFactory>();

            //var redisCache = factory.GetCachingProvider("r1");

            //redisCache.Set<Product>("rkey", new Product() { Name = "test" }, TimeSpan.FromSeconds(20));

            //var redisVal = redisCache.Get<Product>("rkey");

            //Console.WriteLine($"redis cache get value, {redisVal.HasValue} {redisVal.IsNull} {redisVal.Value} ");


            var mCache = factory.GetCachingProvider("m1");

            mCache.Set<Product>("mkey1", new Product() { Name = "test" }, TimeSpan.FromSeconds(20));

            var mVal1 = mCache.Get<Product>("mkey1");


            mCache.Set<string>("mkey", "mvalue", TimeSpan.FromSeconds(20));

            var mVal = mCache.Get<string>("mkey");

            Console.WriteLine($"in-memory cache get value, {mVal.HasValue} {mVal.IsNull} {mVal.Value} ");

            var sCache = factory.GetCachingProvider("s1");

            sCache.Set<string>("skey", "svalue", TimeSpan.FromSeconds(20));

            var sVal = sCache.Get<string>("skey");

            Console.WriteLine($"sqlite cache get value, {sVal.HasValue} {sVal.IsNull} {sVal.Value} ");

            Console.ReadKey();
        }

19 Source : DiskCachingProviderTest.cs
with MIT License
from dotnetcore

protected override IEasyCachingProvider CreateCachingProvider(Action<BaseProviderOptions> additionalSetup)
        {
            IServiceCollection services = new ServiceCollection();
            services.AddEasyCaching(x => 
                x.UseDisk(options => 
                {
                    options.MaxRdSecond = 0;
                    options.DBConfig = new DiskDbOptions
                    {
                        BasePath = Path.GetTempPath()
                    };
                    additionalSetup(options);
                })
            );
            IServiceProvider serviceProvider = services.BuildServiceProvider();
            return serviceProvider.GetService<IEasyCachingProvider>();
        }

19 Source : LiteDBCachingTest.cs
with MIT License
from dotnetcore

protected override IEasyCachingProvider CreateCachingProvider(Action<BaseProviderOptions> additionalSetup)
        {
            IServiceCollection services = new ServiceCollection();
            services.AddEasyCaching(x =>
                x.UseLiteDB(options =>
                {
                    options.DBConfig = new  LiteDBDBOptions
                    {
                        FileName = "s1.ldb"
                    };
                    additionalSetup(options);
                })
            );

            IServiceProvider serviceProvider = services.BuildServiceProvider();
            return serviceProvider.GetService<IEasyCachingProvider>();;
        }

See More Examples