public NinjectServiceScope(
                IResolutionRoot resolver,
                IEnumerable<IParameter> inheritedParameters,
                IServiceProvider parentFallbackProvider)
            {
                if (parentFallbackProvider != null)
                {
                    var scopeFactory = parentFallbackProvider.GetServiceOrDefault<IServiceScopeFactory>();
                    if (scopeFactory != null)
                    {
                        _fallbackScope = scopeFactory.CreateScope();
                        _scope = new KScopeParameter(_fallbackScope.ServiceProvider);
                    }
                }

                if (_scope == null)
                {
                    _scope = new KScopeParameter(parentFallbackProvider);
                }

                inheritedParameters = inheritedParameters.AddOrReplaceScopeParameter(_scope);
                _serviceProvider = new NinjectServiceProvider(resolver, inheritedParameters.ToArray());
            }
 public SessionContainer(IServiceProvider provider)
 {
     scope   = provider?.CreateScope() ?? throw new ArgumentNullException(nameof(scope));
     Context = (SessionContext)scope.ServiceProvider.GetService <ISessionContext>();
 }
示例#3
0
 public BaseSyno(IServiceProvider serviceProvider)
 {
     _serviceProvider = serviceProvider;
     _scope           = _serviceProvider.CreateScope();
 }
        public sealed override async Task <int> ExecuteAsync(CommandContext context, TSettings commandSettings)
        {
            // Set verbose tracing
            if (commandSettings.LogLevel != LogLevel.Information)
            {
                ServiceCollection.Configure <LoggerFilterOptions>(options => options.MinLevel = commandSettings.LogLevel);
            }

            // File logging
            if (!string.IsNullOrEmpty(commandSettings.LogFile))
            {
                // Add the log provider (adding it to the service collection will get picked up by the logger factory)
                ServiceCollection.AddSingleton <ILoggerProvider, FileLoggerProvider>();
                ServiceCollection.Configure <FileLoggerOptions>(options =>
                {
                    options.FileName     = commandSettings.LogFile;
                    options.LogDirectory = string.Empty;
                });
            }

            // Build a temporary service provider so we can log
            // Make sure to place it in it's own scope so transient services get correctly disposed
            IServiceProvider services     = ServiceCollection.BuildServiceProvider();
            ClassCatalog     classCatalog = services.GetService <ClassCatalog>();

            using (IServiceScope serviceScope = services.CreateScope())
            {
                // Log pending messages
                ILogger logger = serviceScope.ServiceProvider.GetRequiredService <ILogger <Bootstrapper> >();
                logger.LogInformation($"Statiq version {Engine.Version}");
                classCatalog?.LogDebugMessagesTo(logger);

                // Debug/Attach
                if (commandSettings.Debug)
                {
                    logger.LogInformation($"Waiting to launch a debugger for process {Process.GetCurrentProcess().Id}...");
                    Debugger.Launch();
                }
                if ((commandSettings.Attach || commandSettings.Debug) && !Debugger.IsAttached)
                {
                    if (commandSettings.Debug)
                    {
                        // If we got here the debug command was unsuccessful
                        logger.LogInformation($"Could not launch a debugger, waiting for manual attach");
                    }
                    logger.LogInformation($"Waiting for a debugger to attach to process {Process.GetCurrentProcess().Id} (or press a key to continue)...");
                    while (!Debugger.IsAttached && !Console.KeyAvailable)
                    {
                        Thread.Sleep(100);
                    }
                    if (Console.KeyAvailable)
                    {
                        Console.ReadKey(true);
                        logger.LogInformation("Key pressed, continuing execution");
                    }
                    else
                    {
                        logger.LogInformation("Debugger attached, continuing execution");
                    }
                }
            }

            // Add settings
            if (commandSettings.Settings?.Length > 0)
            {
                foreach (KeyValuePair <string, string> setting in SettingsParser.Parse(commandSettings.Settings))
                {
                    ConfigurationSettings[setting.Key] = setting.Value;
                }
            }

            // Configure settings after other configuration so they can use the values
            ConfigurableSettings configurableSettings = new ConfigurableSettings(ConfigurationSettings);

            Configurators.Configure(configurableSettings);

            return(await ExecuteCommandAsync(context, commandSettings));
        }
示例#5
0
 public void FetchReplaySetUp()
 {
     Scope  = Services.CreateScope();
     Replay = Scope.ServiceProvider.GetRequiredService <IFetchReplayOperation>();
 }
示例#6
0
 void IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope)
 {
     _callSiteValidator.ValidateResolution(serviceType, scope, _engine.RootScope);
 }
示例#7
0
 public WorkerApplicationOperation(IServiceScope scope)
 {
     ServiceScope = scope;
 }
 public FallbackScope(IServiceScope fallbackScope)
     : this(fallbackScope.ServiceProvider, fallbackScope)
 {
 }
示例#9
0
        private void ProcesSerialData(string line)
        {
            using (IServiceScope scope = scopeFactory.CreateScope())
            {
                HeatAppContext db = scope.ServiceProvider.GetRequiredService <HeatAppContext>();

                if (line == "")
                {
                    return;
                }
                string data = null;
                if (line.Substring(0, 1) == "(" && line.Substring(3, 1) == ")")
                {
                    addr = int.Parse(line.Substring(1, 2), System.Globalization.NumberStyles.HexNumber);
                    data = line.Substring(4);
                }
                else if (line.Substring(0, 1) == "*")
                {
                    var cq = db.Queue.OrderBy(o => o.Sent).Where(w => w.Addr == addr && w.Sent > 0).FirstOrDefault();
                    if (cq != null)
                    {
                        db.Queue.Remove(cq);
                        db.SaveChanges();
                    }
                    data = line.Substring(1);
                }
                else if (line.Substring(0, 1) == "-")
                {
                    data = line.Substring(1);
                }
                else if (line == "}")
                {
                    data = line.Substring(1);
                    addr = 0;
                }
                else
                {
                    addr = 0;
                }

                if (line == "RTC?")
                {
                    DateTime now  = DateTime.Now;
                    string   time = "H" + now.Hour.ToString("x02") + now.Minute.ToString("x02") + now.Second.ToString("x02") + ((int)Math.Round((decimal)now.Millisecond / 10)).ToString("x02");
                    string   date = "Y" + (now.Year - 2000).ToString("x02") + now.Month.ToString("x02") + now.Day.ToString("x02");
                    serialPort.WriteLine(date);
                    serialPort.WriteLine(time);
                }
                else if ((line == "N0?") || (line == "N1?"))
                {
                    int    pr  = 0;
                    int[]  req = { 0, 0, 0, 0 };
                    string v   = "O0000";

                    var res = db.Queue.GroupBy(q => q.Addr).Select(g => new { addr = g.Key, count = g.Count() }).OrderBy(o => o.count).ToList();
                    foreach (var rec in res)
                    {
                        if (rec.addr > 0 && rec.addr < 30)
                        {
                            v = null;
                            if ((line == "N1?") && (rec.count > 20))
                            {
                                v  = "O" + addr.ToString("x02") + pr.ToString("x02");
                                pr = addr;
                                continue;
                            }
                            req[(int)addr / 8] |= (int)Math.Pow(2, (addr % 8));
                        }
                    }
                    if (v == null)
                    {
                        v = "P" + req[0].ToString("x02") + req[1].ToString("x02") + req[3].ToString("x02") + req[3].ToString("x02");
                    }
                    serialPort.WriteLine(v);
                }
                else
                {
                    if (addr > 0)
                    {
                        if (data.Substring(0, 1) == "?")
                        {
                            ExecuteCommands(addr);
                        }
                        else if ((data.Substring(0, 1) == "G" || data.Substring(0, 1) == "S") && data.Substring(1, 1) == "[")
                        {
                            SaveSettings(addr, data);
                        }
                        else if ((data.Substring(0, 1) == "D" || data.Substring(0, 1) == "A") && data.Substring(1, 1) == " ")
                        {
                            SaveState(addr, data);
                        }
                    }
                }
            }
        }
示例#10
0
        private void SaveState(int addr, string message)
        {
            using (IServiceScope scope = scopeFactory.CreateScope())
            {
                HeatAppContext db    = scope.ServiceProvider.GetRequiredService <HeatAppContext>();
                List <string>  items = message.Split(' ').ToList();
                ValveLog       vl    = new ValveLog();
                vl.Addr = addr;
                for (int i = 1; i < items.Count; i++)
                {
                    string item = items[i];
                    switch (item.Substring(0, 1))
                    {
                    case "A":
                        vl.Auto = true;
                        break;

                    case "-":
                        vl.Auto = false;
                        break;

                    case "M":
                        vl.Auto = false;
                        break;

                    case "V":
                        vl.Turn = int.Parse(item.Substring(1));
                        break;

                    case "I":
                        vl.Actual = decimal.Parse(item.Substring(1)) / 100;
                        break;

                    case "S":
                        vl.Wanted = decimal.Parse(item.Substring(1)) / 100;
                        break;

                    case "B":
                        vl.Battery = decimal.Parse(item.Substring(1)) / 1000;
                        break;

                    case "E":
                        vl.Error = int.Parse(item.Substring(1), System.Globalization.NumberStyles.HexNumber);
                        break;

                    case "W":
                        vl.Window = true;
                        break;

                    case "L":
                        vl.Locked = true;
                        break;

                    case "X":
                        //$st['force'] = 1;
                        break;
                    }
                }
                DateTime now = DateTime.Now;
                vl.Time = now;
                db.ValveLog.Add(vl);
                db.SaveChanges();
            }
        }
示例#11
0
        public static void Main(string[] args)
        {
            IWebHost webHost = CreateWebHostBuilder(args).Build();

            using (IServiceScope scopedService = webHost.Services.CreateScope())
            {
                using (EvekilEntity dbContext = scopedService.ServiceProvider.GetRequiredService <EvekilEntity>())
                {
                    if (!dbContext.Languages.Any())
                    {
                        #region Languages
                        Language en = new Language()
                        {
                            Key   = "en",
                            Value = "English"
                        };
                        Language az = new Language()
                        {
                            Key   = "az",
                            Value = "Azerbaijan"
                        };
                        #endregion
                        dbContext.Languages.AddRange(en, az);
                        dbContext.SaveChanges();
                    }
                    if (!dbContext.Advocates.Any())
                    {
                        #region Advocates
                        Advocate NihadAliyev = new Advocate()
                        {
                            Name    = "Nihad",
                            Surname = "Əliyev",
                            Email   = "*****@*****.**",
                            Phone   = 0502503575
                        };
                        #endregion
                        dbContext.Advocates.Add(NihadAliyev);
                        dbContext.SaveChanges();
                    }
                    if (!dbContext.Categories.Any())
                    {
                        #region Categories
                        Category category = new Category()
                        {
                            PhotoPath = "hr1.jpg",
                            Visibilty = true
                        };
                        Category category2 = new Category()
                        {
                            PhotoPath = "hr1.jpg",
                            Visibilty = true
                        };
                        Category category3 = new Category()
                        {
                            PhotoPath = "hr1.jpg",
                            Visibilty = true
                        };
                        Category category4 = new Category()
                        {
                            PhotoPath = "hr1.jpg",
                            Visibilty = true
                        };
                        dbContext.Categories.AddRange(category, category2, category3, category4);
                        dbContext.SaveChanges();


                        CategoryLanguage IR = new CategoryLanguage()
                        {
                            Name        = "İnsan Resursları",
                            Description = @"Bu bölmədə kadrlar şöbəsinin faəliyyətinə aid müxtəlif sənəd nümunələri, o cümlədən əmr formaları, əmək müqavilələri, əmək müqavilələrinə əlavələr, vəzifə təlimatları, aktlar, izahat formaları, ərizələr, əmr kitabları və s. yerləşdirilmişdir.
                                           Diqqətinizə təqdim edilən bu sənəd nümunələri Azərbaycan Respublikasında fəaliyyət göstərən müxtəlif təşkilatlar tərəfindən istifadə edilməkdədir.",
                            CategoryId  = 1,
                            LanguageId  = 2
                        };
                        CategoryLanguage MS = new CategoryLanguage()
                        {
                            Name        = "Məhkəmə Sənədləri",
                            Description = @"Əsasən mülki və iqtisadi mübahisələr üzrə məhkəməyə qədər və məhkəmə araşdırması dövründə tərtib edilən sənəd nümunələri bu bölmədə sizin diqqətinizə təqdim edilir.
                                            Sənəd nümunələri arasında təmənnasız təqdim edilən bəzi iddia ərizələri formaları ilə yanaşı, müxtəlif məzmunlu və formalı vəsatətlər, apellyasiya şikayətləri, kassasiya şikayətləri formaları və s. mövcuddur. Sənəd nümunələri Azərbaycan Respublikası Vəkillər Kollegiyasının üzvləri tərəfindən tərtib edilmişdir. Sənəd nümunələrindən real məhkəmə işlərində istifadə edilmişdir.",
                            CategoryId  = 2,
                            LanguageId  = 2
                        };
                        CategoryLanguage M = new CategoryLanguage()
                        {
                            Name        = "Müqavilələr",
                            Description = @"Azərbaycan Respublikasının qanunvericiliyinə uyğun tərtib edilən müxtəlif müqavilə növləri. Təqdim edilən bütün müqavilə növləri təcrübədə istifadə edilmişdir.
                                           Müqavilələr arasında tez-tez istifadə edilən alğı-satqı, bağışlama, podrat, xidmət müqavilələri ilə yanaşı Azərbaycan işgüzar adətlərində yeni-yeni rast gəlinən autsorsinq, birgə əməliyyat sazişləri nümunələri də daxil edilmişdir.",
                            CategoryId  = 3,
                            LanguageId  = 2
                        };
                        CategoryLanguage SS = new CategoryLanguage()
                        {
                            Name        = "Sair Sənədlər",
                            Description = @"Yuxarıdakı təsnifata yer almamış sənəd nümunələrini hazırki bölmədə yerləşdirərək diqqətinizə çatdırırıq. Bu bölmədə hüquqi şəxsin təsis sənədləri nümunələri, informasiya sorğuları, şikayət ərizələri, prtokol formaları, etibarnamələr, müraciət ərizələri və s. sənəd nümunələri yerləşdirilmişdir.
                                           We understand business. That's why we begin every project with a workshop — crafting a one-of-a-kind, unique strategy that is designed to help you win.",
                            CategoryId  = 4,
                            LanguageId  = 2
                        };
                        #endregion
                        dbContext.CategoryLanguages.AddRange(IR, M, MS, SS);
                        dbContext.SaveChanges();
                    }
                    if (!dbContext.Subcategories.Any())
                    {
                        #region Subcategories

                        #region InsanResurslariSubcategoriyasi
                        Subcategory _EM = new Subcategory()
                        {
                            CategoryId = 1
                        };
                        Subcategory _EF = new Subcategory()
                        {
                            CategoryId = 1
                        };
                        Subcategory _VT = new Subcategory()
                        {
                            CategoryId = 1
                        };
                        Subcategory _E = new Subcategory()
                        {
                            CategoryId = 1
                        };
                        Subcategory _EK = new Subcategory()
                        {
                            CategoryId = 1
                        };
                        Subcategory _EV = new Subcategory()
                        {
                            CategoryId = 1
                        };
                        Subcategory _A = new Subcategory()
                        {
                            CategoryId = 1
                        };
                        dbContext.Subcategories.AddRange(_EM, _EF, _VT, _E, _EK, _EV, _A);
                        dbContext.SaveChanges();

                        SubcategoryLanguage EM = new SubcategoryLanguage()
                        {
                            Name          = "Əmək Müqaviləsi",
                            SubcategoryId = 1,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage EF = new SubcategoryLanguage()
                        {
                            Name          = "Əmr Formaları",
                            SubcategoryId = 2,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage VT = new SubcategoryLanguage()
                        {
                            Name          = "Vəzifə Təlimatları",
                            SubcategoryId = 3,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage E = new SubcategoryLanguage()
                        {
                            Name          = "Ərizələr",
                            SubcategoryId = 4,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage EK = new SubcategoryLanguage()
                        {
                            Name          = "Əmr Kitabları",
                            SubcategoryId = 5,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage EV = new SubcategoryLanguage()
                        {
                            Name          = "Ezamiyyə Vərəqələri",
                            SubcategoryId = 6,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage A = new SubcategoryLanguage()
                        {
                            Name          = "Aktlar",
                            SubcategoryId = 7,
                            LanguageId    = 2
                        };
                        #endregion

                        #region MehkemeSenedleriSubcategoriyasi
                        Subcategory _IE = new Subcategory()
                        {
                            CategoryId = 2
                        };
                        Subcategory _AS = new Subcategory()
                        {
                            CategoryId = 2
                        };
                        Subcategory _KS = new Subcategory()
                        {
                            CategoryId = 2
                        };
                        Subcategory _V = new Subcategory()
                        {
                            CategoryId = 2
                        };
                        Subcategory _BS = new Subcategory()
                        {
                            CategoryId = 2
                        };
                        Subcategory _QIE = new Subcategory()
                        {
                            CategoryId = 2
                        };
                        Subcategory _ET = new Subcategory()
                        {
                            CategoryId = 2
                        };
                        dbContext.Subcategories.AddRange(_IE, _AS, _KS, _V, _BS, _QIE, _ET);
                        dbContext.SaveChanges();

                        SubcategoryLanguage IE = new SubcategoryLanguage()
                        {
                            Name          = "İddia Ərizələri",
                            SubcategoryId = 8,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage AS = new SubcategoryLanguage()
                        {
                            Name          = "Apelyasiya Şikayətləri",
                            SubcategoryId = 9,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage KS = new SubcategoryLanguage()
                        {
                            Name          = "Kassasiya Şikayətləri",
                            SubcategoryId = 10,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage V = new SubcategoryLanguage()
                        {
                            Name          = "Vəsatətlər",
                            SubcategoryId = 11,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage BS = new SubcategoryLanguage()
                        {
                            Name          = "Barışıq Sazişləri",
                            SubcategoryId = 12,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage QIE = new SubcategoryLanguage()
                        {
                            Name          = "Qarşılıqlı İddia Ərizələri",
                            SubcategoryId = 13,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage ET = new SubcategoryLanguage()
                        {
                            Name          = "Etirazlar",
                            SubcategoryId = 14,
                            LanguageId    = 2
                        };
                        #endregion

                        #region MuqavilelerSubcategoriyasi
                        Subcategory _ASM = new Subcategory()
                        {
                            CategoryId = 3
                        };
                        Subcategory _PM = new Subcategory()
                        {
                            CategoryId = 3
                        };
                        Subcategory _XM = new Subcategory()
                        {
                            CategoryId = 3
                        };
                        Subcategory _BM = new Subcategory()
                        {
                            CategoryId = 3
                        };
                        Subcategory _DM = new Subcategory()
                        {
                            CategoryId = 3
                        };
                        Subcategory _ME = new Subcategory()
                        {
                            CategoryId = 3
                        };
                        Subcategory _IM = new Subcategory()
                        {
                            CategoryId = 3
                        };
                        dbContext.Subcategories.AddRange(_ASM, _PM, _XM, _BM, _DM, _ME, _IM);
                        dbContext.SaveChanges();

                        SubcategoryLanguage ASM = new SubcategoryLanguage()
                        {
                            Name          = "Alğı-satqı Müqavilələri",
                            SubcategoryId = 15,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage PM = new SubcategoryLanguage()
                        {
                            Name          = "Podrat Müqavilələri",
                            SubcategoryId = 16,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage XM = new SubcategoryLanguage()
                        {
                            Name          = "Xidmət Müqavilələri",
                            SubcategoryId = 17,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage BM = new SubcategoryLanguage()
                        {
                            Name          = "Borc Müqavilələri",
                            SubcategoryId = 18,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage DM = new SubcategoryLanguage()
                        {
                            Name          = "Daşınma Müqavilələri",
                            SubcategoryId = 19,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage ME = new SubcategoryLanguage()
                        {
                            Name          = "Müqavilələrə Əlavələr",
                            SubcategoryId = 20,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage IM = new SubcategoryLanguage()
                        {
                            Name = "İcarə Müqavilələri" +
                                   "",
                            SubcategoryId = 21,
                            LanguageId    = 2
                        };
                        #endregion

                        #region SairSenedlerSubcategoriyasi
                        Subcategory _HSUY = new Subcategory()
                        {
                            CategoryId = 4
                        };
                        Subcategory _EUMEF = new Subcategory()
                        {
                            CategoryId = 4
                        };
                        Subcategory _ES = new Subcategory()
                        {
                            CategoryId = 4
                        };
                        Subcategory _TQ = new Subcategory()
                        {
                            CategoryId = 4
                        };
                        Subcategory _VF = new Subcategory()
                        {
                            CategoryId = 4
                        };
                        Subcategory _Akt = new Subcategory()
                        {
                            CategoryId = 4
                        };
                        Subcategory _QF = new Subcategory()
                        {
                            CategoryId = 4
                        };
                        dbContext.Subcategories.AddRange(_HSUY, _EUMEF, _ES, _TQ, _VF, _Akt, _QF);
                        dbContext.SaveChanges();

                        SubcategoryLanguage HSUY = new SubcategoryLanguage()
                        {
                            Name          = "Hüquqi Şəxsin Ümumi Yığıncağının Qərarı",
                            SubcategoryId = 22,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage EUMEF = new SubcategoryLanguage()
                        {
                            Name          = "Əfv üçün Müraciət Ərizə Forması",
                            SubcategoryId = 23,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage ES = new SubcategoryLanguage()
                        {
                            Name          = "Etibarnamələr",
                            SubcategoryId = 24,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage TQ = new SubcategoryLanguage()
                        {
                            Name          = "Təsisçinin Qərarı",
                            SubcategoryId = 25,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage VF = new SubcategoryLanguage()
                        {
                            Name          = "Vəsiyyətnamə Formaları",
                            SubcategoryId = 26,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage Akt = new SubcategoryLanguage()
                        {
                            Name          = "Aktlar",
                            SubcategoryId = 27,
                            LanguageId    = 2
                        };
                        SubcategoryLanguage QF = new SubcategoryLanguage()
                        {
                            Name          = "Qərar Formaları",
                            SubcategoryId = 28,
                            LanguageId    = 2
                        };
                        #endregion
                        #endregion
                        dbContext.SubcategoryLanguages.AddRange(EM, EF, VT, E, EK, EV, A, IE, AS, KS, V, BS, QIE, ET, ASM, PM, XM, BM, DM, ME, IM, HSUY, EUMEF, ES, TQ, VF, Akt, QF);
                        dbContext.SaveChanges();
                    }
                    //   UserAndRoleCreater.CreateAsync(scopedService, dbContext).Wait();
                }
            }

            webHost.Run();
        }
示例#12
0
        public BackgroundFileUploader(IServiceProvider serviceProvider)
        {
            IServiceScope newScope = serviceProvider.CreateScope();

            _context = newScope.ServiceProvider.GetService <PuzzleServerContext>();
        }
 private TestCircuitHost(string circuitId, IServiceScope scope, CircuitClientProxy client, RendererRegistry rendererRegistry, RemoteRenderer renderer, IReadOnlyList <ComponentDescriptor> descriptors, RemoteJSRuntime jsRuntime, CircuitHandler[] circuitHandlers, ILogger logger)
     : base(circuitId, scope, client, rendererRegistry, renderer, descriptors, jsRuntime, circuitHandlers, logger)
 {
 }
 public Scope(IServiceScope serviceScope)
 => this.serviceScope = serviceScope ?? throw new ArgumentNullException(nameof(serviceScope));
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    Context.RequestServices = PriorRequestServices;
                    Context.ApplicationServices = PriorAppServices;
                }

                if (Scope != null)
                {
                    Scope.Dispose();
                    Scope = null;
                }

                Context = null;
                PriorAppServices = null;
                PriorRequestServices = null;

                disposedValue = true;
            }
        }
示例#16
0
 /// <summary>
 /// Retrieves the required service from the ServiceHost
 /// </summary>
 /// <typeparam name="T">Type of service to retrieve</typeparam>
 /// <param name="viewModel">The target view model</param>
 /// <param name="scope">An existing scope to use</param>
 /// <returns></returns>
 public static T GetRequiredService <T>(this ViewModel viewModel, IServiceScope scope) => scope.ServiceProvider.GetRequiredService <T>();
示例#17
0
        protected override T OnResolve <T>()
        {
            _lifetimeScope = _lifetimeScope ?? _services.Value.CreateScope();

            return(ActivatorUtilities.GetServiceOrCreateInstance <T>(_lifetimeScope.ServiceProvider));
        }
示例#18
0
 public JobTrackingInfo(IServiceScope scope) => Scope = scope;
示例#19
0
 public virtual void Dispose()
 {
     _lifetimeScope?.Dispose();
     _lifetimeScope = null;
 }
 private async Task SetupAssetData(IServiceScope scope)
 {
     var assetService = scope.ServiceProvider.GetRequiredService <IAssetService>();
     await assetService.CreateAssetAsync(_asset);
 }
 public DeliveryRequestMessageHandler(IServiceScope serviceScope, IMessageExchangeSerializer serializer, string warehouseRouteKey)
 {
     _serviceScope      = serviceScope;
     _serializer        = serializer;
     _warehouseRouteKey = warehouseRouteKey;
 }
示例#22
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions <CorsOptions> cors)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStatusCodePages(async statusCodeContext =>
            {
                statusCodeContext.HttpContext.Response.ContentType = MediaTypeNames.Application.Json;

                ErrorResource details = new ErrorResource
                {
                    StatusCode = statusCodeContext.HttpContext.Response.StatusCode,
                    Message    = ReasonPhrases.GetReasonPhrase(statusCodeContext.HttpContext.Response.StatusCode),
                };

                string json = JsonSerializer.Serialize(details);

                await statusCodeContext.HttpContext.Response.WriteAsync(json);
            });

            // Perform database migration
            using IServiceScope serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope();
            using ChatContext dbContext      = serviceScope.ServiceProvider.GetRequiredService <ChatContext>();
            dbContext.Database.Migrate();

            // Use swagger UI
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/master/swagger.json", "Chat Client Web API");
                options.DocExpansion(DocExpansion.List);
                options.EnableFilter();
                options.DisplayRequestDuration();
                options.ShowExtensions();
                options.ShowCommonExtensions();
                options.EnableValidator();
                options.EnableDeepLinking();
            });

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors(builder =>
            {
                builder.WithOrigins(cors.Value.AllowedOrigins);
                builder.WithMethods(cors.Value.AllowedMethods);
                builder.WithHeaders(cors.Value.AllowedHeaders);
                builder.AllowCredentials();
            });

            app.UseAuthentication();

            app.UseAuthorization();

            CultureInfo culture = new CultureInfo("en-GB");

            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture(culture),
                SupportedCultures     = new List <CultureInfo> {
                    culture
                },
                SupportedUICultures = new List <CultureInfo> {
                    culture
                },
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub <ChatHubBase>("/chat");
                endpoints.MapControllers();
            });
        }
示例#23
0
 protected T Create <T>(IServiceScope scope)
     where T : IUnitOfWork
 {
     return(scope.ServiceProvider.GetService <T>());
 }
示例#24
0
 public void FetchReplayTearDown()
 {
     Replay = null;
     Scope.Dispose();
     Scope = null;
 }
示例#25
0
 public UpdateProductCounterByReserveMessageHandler(IServiceScope serviceScope, IMessageExchangeSerializer serializer)
 {
     _serviceScope = serviceScope;
     _serializer   = serializer;
 }
示例#26
0
 public TestRunner(IServiceProvider serviceProvider)
 {
     _serviceScope         = serviceProvider.CreateScope();
     _videoStreamProcessor = _serviceScope.ServiceProvider.GetRequiredService <VideoStreamProcessor>();
 }
        public static async Task SeedProductAsync(IServiceScope serviceScope)
        {
            var dbContext = serviceScope.ServiceProvider.GetRequiredService <DataContext>();

            if (!await dbContext.Categories.AnyAsync() || !await dbContext.Products.AnyAsync())
            {
                var category = new Category {
                    Name = "Art"
                };
                await dbContext.Categories.AddAsync(category);

                await dbContext.Products.AddAsync(new Product
                {
                    Category = category,
                    Name     = "Litle",
                    Price    = 50
                });

                await dbContext.Products.AddAsync(new Product
                {
                    Category = category,
                    Name     = "Medium",
                    Price    = 100
                });

                await dbContext.Products.AddAsync(new Product
                {
                    Category = category,
                    Name     = "Large",
                    Price    = 150
                });

                await dbContext.Products.AddAsync(new Product
                {
                    Category = category,
                    Name     = "ExtraLarge",
                    Price    = 200
                });

                var category2 = new Category {
                    Name = "PaintColor"
                };
                await dbContext.Categories.AddAsync(category2);

                await dbContext.Products.AddAsync(new Product
                {
                    Category = category2,
                    Name     = "Pink",
                    Price    = 200
                });

                await dbContext.Products.AddAsync(new Product
                {
                    Category = category2,
                    Name     = "White",
                    Price    = 200
                });

                await dbContext.Products.AddAsync(new Product
                {
                    Category = category2,
                    Name     = "Green",
                    Price    = 200
                });

                await dbContext.Products.AddAsync(new Product
                {
                    Category = category2,
                    Name     = "Blue",
                    Price    = 200
                });

                await dbContext.Products.AddAsync(new Product
                {
                    Category = category2,
                    Name     = "Red",
                    Price    = 200
                });

                await dbContext.SaveChangesAsync();
            }
        }
示例#28
0
        public async Task SeedAsync(IServiceScope scope)
        {
            bool smthChanged = false;
            UserManager <AppUser>      _userManager = scope.ServiceProvider.GetRequiredService <UserManager <AppUser> >();
            RoleManager <IdentityRole> _roleManager = scope.ServiceProvider.GetRequiredService <RoleManager <IdentityRole> >();

            if (!_roleManager.Roles.Any())
            {
                IdentityRole userRole = new IdentityRole();
                userRole.Name = "User";

                await _roleManager.CreateAsync(userRole);

                smthChanged = true;
            }


            if (!_userManager.Users.Any())
            {
                AppUser user1 = new AppUser()
                {
                    Name     = "User1",
                    Surname  = "Userov1",
                    Email    = "*****@*****.**",
                    UserName = "******"
                };

                AppUser user2 = new AppUser()
                {
                    Name     = "User2",
                    Surname  = "Userov2",
                    Email    = "*****@*****.**",
                    UserName = "******"
                };

                AppUser user3 = new AppUser()
                {
                    Name     = "User3",
                    Surname  = "Userov3",
                    Email    = "*****@*****.**",
                    UserName = "******"
                };

                await _userManager.CreateAsync(user1, "User123@");

                await _userManager.AddToRoleAsync(user1, "User");

                await _userManager.CreateAsync(user2, "User123@");

                await _userManager.AddToRoleAsync(user2, "User");

                await _userManager.CreateAsync(user3, "User123@");

                await _userManager.AddToRoleAsync(user3, "User");

                smthChanged = true;
            }

            if (smthChanged)
            {
                await SaveChangesAsync();
            }
        }
示例#29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AsyncServiceScope"/> struct.
 /// Wraps an instance of <see cref="IServiceScope" />.
 /// <param name="serviceScope">The <see cref="IServiceScope"/> instance to wrap.</param>
 /// </summary>
 public AsyncServiceScope(IServiceScope serviceScope)
 {
     _serviceScope = serviceScope ?? throw new ArgumentNullException(nameof(serviceScope));
 }
示例#30
0
 public ODataController()
 {
     IServiceProvider rootContainer = null; // Get container from some request context
     scope = rootContainer.GetService<IServiceScopeFactory>().CreateScope();
 }
        private object CreateParameter <TInput>(IDurableEntityContext ctx, ParameterInfo k, IServiceScope scope)
        {
            if (k.ParameterType == typeof(TInput))
            {
                return(ctx.GetInput <TInput>());
            }


            if (k.ParameterType == typeof(ILogger))
            {
                var loggerFactory = scope.ServiceProvider.GetRequiredService <ILoggerFactory>();
                var logger        = loggerFactory.CreateLogger($"Entity.{Name}.{ctx.OperationName}");
                logger.BeginScope(new Dictionary <string, string> {
                    ["OperationName"] = ctx.OperationName
                });

                return(logger);
            }

            return(scope.ServiceProvider.GetService(k.ParameterType));
        }
 public AspNetCoreJobActivatorScope([NotNull] IServiceScope serviceScope)
 {
     if (serviceScope == null) throw new ArgumentNullException(nameof(serviceScope));
     _serviceScope = serviceScope;
 }
示例#33
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-us");
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

            Log.LogInformation("Starting bot background service.");

            IServiceScope scope = null;

            try
            {
                // Create a new scope for the session.
                scope = _provider.CreateScope();

                Log.LogTrace("Registering listeners for Discord client events.");

                _client.LatencyUpdated  += OnLatencyUpdated;
                _client.Disconnected    += OnDisconnect;
                _client.MessageReceived += HandleCommand;

                _client.Log     += _serilogAdapter.HandleLog;
                _restClient.Log += _serilogAdapter.HandleLog;
                _commands.Log   += _serilogAdapter.HandleLog;

                _commands.CommandExecuted += HandleCommandResultAsync;

                // Register with the cancellation token so we can stop listening to client events if the service is
                // shutting down or being disposed.
                stoppingToken.Register(OnStopping);

                Log.LogInformation("Running database migrations.");
                scope.ServiceProvider.GetRequiredService <ModixContext>()
                .Database.Migrate();

                Log.LogInformation("Starting behaviors.");
                await scope.ServiceProvider.GetRequiredService <IBehaviourConfigurationService>()
                .LoadBehaviourConfiguration();

                foreach (var behavior in scope.ServiceProvider.GetServices <IBehavior>())
                {
                    await behavior.StartAsync();

                    stoppingToken.Register(() => behavior.StopAsync().GetAwaiter().GetResult());
                }

                // The only thing that could go wrong at this point is the client failing to login and start. Promote
                // our local service scope to a field so that it's available to the HandleCommand method once events
                // start firing after we've connected.
                _scope = scope;

                Log.LogInformation("Loading command modules...");

                await _commands.AddModulesAsync(typeof(ModixBot).Assembly, _scope.ServiceProvider);

                Log.LogInformation("{Modules} modules loaded, containing {Commands} commands",
                                   _commands.Modules.Count(), _commands.Modules.SelectMany(d => d.Commands).Count());

                Log.LogInformation("Logging into Discord and starting the client.");

                await StartClient(stoppingToken);

                Log.LogInformation("Discord client started successfully.");

                await Task.Delay(-1);
            }
            catch (Exception ex)
            {
                Log.LogError(ex, "An error occurred while attempting to start the background service.");

                try
                {
                    OnStopping();

                    Log.LogInformation("Logging out of Discord.");
                    await _client.LogoutAsync();
                }
                finally
                {
                    scope?.Dispose();
                    _scope = null;
                }

                throw;
            }

            void OnStopping()
            {
                Log.LogInformation("Stopping background service.");

                _client.Disconnected    -= OnDisconnect;
                _client.LatencyUpdated  -= OnLatencyUpdated;
                _client.MessageReceived -= HandleCommand;

                _client.Log     -= _serilogAdapter.HandleLog;
                _commands.Log   -= _serilogAdapter.HandleLog;
                _restClient.Log -= _serilogAdapter.HandleLog;

                _commands.CommandExecuted -= HandleCommandResultAsync;

                foreach (var context in _commandScopes.Keys)
                {
                    _commandScopes.TryRemove(context, out var commandScope);
                    commandScope?.Dispose();
                }
            }
        }
 /// <summary>
 /// Disposes the current scoped request services.
 /// </summary>
 public void Dispose()
 {
     this.scope?.Dispose();
     this.scope = null;
     this.requestServices = null;
 }
示例#35
0
 public ScopedJob(IServiceScope scope, IJob innerJob)
 {
     _scope    = scope;
     _innerJob = innerJob;
 }
示例#36
0
 public void Dispose()
 {
     _scope?.Dispose();
     _scope = null;
     _requestServices = null;
 }
 public MiddlewareRunner(IServiceScope scope)
 {
     _scope = scope;
 }