Esempio n. 1
0
        public void DbContextPoolTest()
        {
            int hashCode1, hashCode2;
            var services = new ServiceCollection();

            services.AddScoped <DbTest>();
            using (var scope = ObjectProviderFactory.CreateScope(provider => provider.RegisterInstance(new DbTest(3))))
            {
                var dbContext = scope.GetService <DemoDbContext>();
                hashCode1 = dbContext.GetHashCode();
                dbContext.Database.AutoTransactionsEnabled = false;
                var dbTest = scope.GetService <DbTest>();
                Assert.Equal(3, dbTest.Count);
            }

            using (var scope = ObjectProviderFactory.CreateScope(provider => provider.RegisterInstance(new DbTest(1))))
            {
                var dbContext = scope.GetService <DemoDbContext>();
                hashCode2 = dbContext.GetHashCode();
                Assert.True(dbContext.Database.AutoTransactionsEnabled);
                var dbTest = scope.GetService <DbTest>();
                Assert.Equal(1, dbTest.Count);
            }

            Assert.Equal(hashCode1, hashCode2);
        }
Esempio n. 2
0
        public async Task GetUsersTest()
        {
            using (var scope = ObjectProviderFactory.CreateScope())
            {
                var serviceProvider = scope.GetService <IServiceProvider>();
                if (serviceProvider == null)
                {
                    var logger = ObjectProviderFactory.GetService <ILoggerFactory>().CreateLogger(GetType());
                    logger.LogError((scope as ObjectProvider)?.UnityContainer.Registrations.ToJson());
                    Assert.NotNull(serviceProvider);
                }
                var dbContext = scope.GetService <DemoDbContext>();
                var users     = await dbContext.Users
                                //.Include(u => u.Cards)
                                .FindAll(u => !string.IsNullOrWhiteSpace(u.Name))
                                .Take(10)
                                .ToArrayAsync();

                foreach (var u in users)
                {
                    await u.LoadCollectionAsync(u1 => u1.Cards);

                    Assert.Equal(u.GetDbContext <DemoDbContext>().GetHashCode(), dbContext.GetHashCode());
                }
            }
        }
Esempio n. 3
0
        public EntityFrameworkTests()
        {
            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            Configuration.Instance
            //.UseMicrosoftDependencyInjection()
            //.UseUnityContainer()
            .UseAutofacContainer()
            .UseConfiguration(builder.Build())
            .UseCommonComponents()
            .UseJsonNet()
            .UseLog4Net()
            .UseDbContextPool <DemoDbContext>(options =>
            {
                options.EnableSensitiveDataLogging();
                options.UseMySQL(Configuration.Instance.GetConnectionString(DemoDbContextFactory.MySqlConnectionStringName));
                //options.UseInMemoryDatabase(nameof(DemoDbContext));
                //options.UseSqlServer(Configuration.Instance.GetConnectionString(DemoDbContextFactory.ConnectionStringName));
            }, 1000);

            ObjectProviderFactory.Instance.Build();
            using (var serviceScope = ObjectProviderFactory.CreateScope())
            {
                var dbContext = serviceScope.GetService <DemoDbContext>();
                dbContext.Database.Migrate();
            }
        }
Esempio n. 4
0
        public async Task AddPresonTest()
        {
            try
            {
                var id = DateTime.Now.Ticks;
                using (var serviceScope = ObjectProviderFactory.CreateScope())
                {
                    var dbContext = serviceScope.GetService <DemoDbContext>();
                    var person    = new Person(id, "ivan");
                    dbContext.Persons.Add(person);
                    await dbContext.SaveChangesAsync();
                }

                using (var serviceScope = ObjectProviderFactory.CreateScope())
                {
                    var dbContext = serviceScope.GetService <DemoDbContext>();
                    var person    = await dbContext.Persons.FindAsync(id).ConfigureAwait(false);

                    Assert.NotNull(person);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Esempio n. 5
0
 public async Task Test1()
 {
     using (var scope = ObjectProviderFactory.CreateScope())
     {
         var service = scope.GetService <IAliPayBankCardParseService>();
         var result  = await service.ParseBankCardAsync(cardNo : "6217920159440572");
     }
 }
Esempio n. 6
0
        public async Task CrudTest()
        {
            User user = null;

            using (var scope = ObjectProviderFactory.CreateScope())
            {
                var dbCtx = scope.GetRequiredService <DemoDbContext>();

                var unitOfWork = scope.GetRequiredService <IUnitOfWork>();
                var repository = scope.GetRequiredService <IDemoRepository>();
                user = new User($"ivan-{DateTime.Now.Ticks}", "male");
                repository.Add(user);
                await unitOfWork.CommitAsync()
                .ConfigureAwait(false);
            }
            var newName = $"new name {DateTime.Now.Ticks}";

            using (var scope = ObjectProviderFactory.CreateScope())
            {
                var repository = scope.GetRequiredService <IDemoRepository>();
                var unitOfWork = scope.GetRequiredService <IUnitOfWork>();
                user = await repository.GetByKeyAsync <User>(user.Id)
                       .ConfigureAwait(false);

                Assert.NotNull(user);
                user.ModifyName(newName);
                var dbCtx = scope.GetRequiredService <DemoDbContext>();

                await unitOfWork.CommitAsync()
                .ConfigureAwait(false);
            }

            using (var scope = ObjectProviderFactory.CreateScope())
            {
                var repository = scope.GetRequiredService <IDemoRepository>();
                var unitOfWork = scope.GetRequiredService <IUnitOfWork>();
                user = await repository.GetByKeyAsync <User>(user.Id)
                       .ConfigureAwait(false);

                Assert.True(user.Name == newName);
                repository.Remove(user);
                await unitOfWork.CommitAsync()
                .ConfigureAwait(false);
            }

            using (var scope = ObjectProviderFactory.CreateScope())
            {
                var repository = scope.GetRequiredService <IDemoRepository>();
                user = await repository.GetByKeyAsync <User>(user.Id)
                       .ConfigureAwait(false);

                Assert.Null(user);
            }
        }
Esempio n. 7
0
        public async Task InnerJoinTest()
        {
            using (var scope = ObjectProviderFactory.CreateScope())
            {
                var repository = scope.GetRequiredService <IDemoRepository>();
                var query      = from user in repository.FindAll <User>()
                                 join card in repository.FindAll <Card>()
                                 on user.Id equals card.Id
                                 select new { user.Id, card.Name };

                var sql    = query.ToString();
                var result = await query.ToListAsync();
            }
        }
Esempio n. 8
0
        public async Task AddUserTest()
        {
            using (var serviceScope = ObjectProviderFactory.CreateScope())
                using (var scope = new TransactionScope(TransactionScopeOption.Required,
                                                        new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadCommitted
                },
                                                        TransactionScopeAsyncFlowOption.Enabled))
                {
                    var serviceProvider = serviceScope.GetService <IServiceProvider>();
                    if (serviceProvider == null)
                    {
                        Assert.NotNull(serviceProvider);
                    }

                    try
                    {
                        var dbContext = serviceScope.GetService <DemoDbContext>();
                        if (dbContext == null)
                        {
                            var logger = ObjectProviderFactory.GetService <ILoggerFactory>().CreateLogger(GetType());
                            logger.LogError((serviceScope as ObjectProvider)?.UnityContainer.Registrations.ToJson());
                            Assert.NotNull(dbContext);
                        }

                        var user = new User("ivan", "male");
                        user.AddCard("ICBC");
                        user.AddCard("CCB");
                        user.AddCard("ABC");

                        dbContext.Users.Add(user);
                        await dbContext.SaveChangesAsync();

                        scope.Complete();
                        var client   = dbContext.GetMongoDbClient();
                        var database = dbContext.GetMongoDbDatabase();
                        var conn     = dbContext.GetMongoDbConnection();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        throw;
                    }
                }
        }
Esempio n. 9
0
 public async Task AddPresonTest()
 {
     try
     {
         using (var serviceScope = ObjectProviderFactory.CreateScope())
         {
             var dbContext = serviceScope.GetService <DemoDbContext>();
             var person    = new Person("ivan");
             dbContext.Persons.Add(person);
             await dbContext.SaveChangesAsync();
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
Esempio n. 10
0
        public async Task GetUsersTest()
        {
            using (var scope = ObjectProviderFactory.CreateScope())
            {
                var serviceProvider = scope.GetService <IServiceProvider>();
                if (serviceProvider == null)
                {
                    var logger = ObjectProviderFactory.GetService <ILoggerFactory>().CreateLogger(GetType());
                    logger.LogError((scope as ObjectProvider)?.UnityContainer.Registrations.ToJson());
                    Assert.NotNull(serviceProvider);
                }

                //var options = new DbContextOptionsBuilder<DemoDbContext>();
                //options.UseMongoDb(Configuration.Instance.GetConnectionString(DemoDbContextFactory.MongoDbConnectionStringName));

                var dbContext = scope.GetService <DemoDbContext>();

                try
                {
                    var user = await dbContext.Users.FindAsync("5BEE29960CCE411C20215A17").ConfigureAwait(false);

                    // var connection = dbContext.GetMongoDbDatabase();
                    var users = await dbContext.Users
                                //.Include(u => u.Cards)
                                //.FindAll(u => !string.IsNullOrWhiteSpace(u.Name))
                                .Take(10)
                                .ToListAsync()
                                .ConfigureAwait(false);

                    //foreach (var u in users)
                    //{
                    //    await u.LoadCollectionAsync(u1 => u1.Cards);
                    //    Assert.True(u.Cards.Count > 0);
                    //    //Assert.Equal(u.GetDbContext<DemoDbContext>().GetHashCode(), dbContext.GetHashCode());
                    //}
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
        }
Esempio n. 11
0
        public async Task DbContextPoolScopeTest()
        {
            var tasks = new object[10].Select(o => Task.Run(() =>
            {
                using (var scope = ObjectProviderFactory.CreateScope())
                {
                    var dbCtx    = scope.GetService <DemoDbContext>();
                    var hashCode = dbCtx.GetHashCode();

                    dbCtx = scope.GetService <DemoDbContext>();
                    Assert.Equal(hashCode, dbCtx.GetHashCode());

                    dbCtx = scope.GetService <DemoDbContext>();
                    Assert.Equal(hashCode, dbCtx.GetHashCode());

                    _output.WriteLine($"dbctx hashcode  {hashCode}");
                }
            })).ToArray();
            await Task.WhenAll(tasks);

            tasks = new object[10].Select(o => Task.Run(() =>
            {
                using (var scope = ObjectProviderFactory.CreateScope())
                {
                    var dbCtx    = scope.GetService <DemoDbContext>();
                    var hashCode = dbCtx.GetHashCode();

                    dbCtx = scope.GetService <DemoDbContext>();
                    Assert.Equal(hashCode, dbCtx.GetHashCode());

                    dbCtx = scope.GetService <DemoDbContext>();
                    Assert.Equal(hashCode, dbCtx.GetHashCode());

                    _output.WriteLine($"dbctx hashcode  {hashCode}");
                }
            })).ToArray();
            await Task.WhenAll(tasks);
        }
Esempio n. 12
0
        public async Task ConcurrentUdpateTest()
        {
            using (var serviceScope = ObjectProviderFactory.CreateScope())
            {
                var concurrencyProcessor = serviceScope.GetService <IConcurrencyProcessor>();
                var dbContext            = serviceScope.GetService <DemoDbContext>();
                using (var transactionScope = new TransactionScope(TransactionScopeOption.Required,
                                                                   new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadCommitted
                },
                                                                   TransactionScopeAsyncFlowOption.Enabled))
                {
                    await concurrencyProcessor.ProcessAsync(async() =>
                    {
                        var account = await dbContext.Users.FirstOrDefaultAsync();
                        account.ModifyName($"ivan{DateTime.Now}");
                        await dbContext.SaveChangesAsync();
                    });

                    transactionScope.Complete();
                }
            }
        }
Esempio n. 13
0
        private void RemoveMessages(CancellationTokenSource cancellationTokenSource)
        {
            while (!cancellationTokenSource.IsCancellationRequested)
            {
                try
                {
                    var             toRemoveMessages = new List <ToRemoveMessage>();
                    ToRemoveMessage toRemoveMessage  = null;
                    do
                    {
                        _toRemoveMessages.TryDequeue(out toRemoveMessage);
                        if (toRemoveMessage != null)
                        {
                            toRemoveMessages.Add(toRemoveMessage);
                        }
                    } while (toRemoveMessages.Count < 10 && toRemoveMessage != null);

                    if (toRemoveMessages.Count == 0)
                    {
                        Task.Delay(1000).Wait();
                    }
                    else
                    {
                        using (var scope = ObjectProviderFactory.CreateScope())
                        {
                            var messageStore = scope.GetService <IMessageStore>() as MessageStore;
                            if (messageStore == null)
                            {
                                throw new Exception("invalid messagestore!");
                            }


                            var toRemoveCommands = toRemoveMessages.Where(rm => rm.Type == MessageType.Command)
                                                   .Select(rm => rm.MessageId)
                                                   .ToArray();
                            if (toRemoveCommands.Length > 0)
                            {
                                RemoveUnSentCommands(messageStore, toRemoveCommands);
                            }

                            var toRemoveEvents = toRemoveMessages.Where(rm => rm.Type == MessageType.Event)
                                                 .Select(rm => rm.MessageId)
                                                 .ToArray();
                            if (toRemoveEvents.Length > 0)
                            {
                                RemoveUnPublishedEvents(messageStore, toRemoveEvents);
                            }

                            messageStore.SaveChanges();
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    return;
                }
                catch (ThreadAbortException)
                {
                    return;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"remove Messages Processing faield!");
                }
            }
        }
Esempio n. 14
0
        private void RemoveMessages(CancellationTokenSource cancellationTokenSource)
        {
            while (!cancellationTokenSource.IsCancellationRequested)
            {
                try
                {
                    var             toRemoveMessages = new List <ToRemoveMessage>();
                    ToRemoveMessage toRemoveMessage  = null;
                    do
                    {
                        _toRemoveMessages.TryDequeue(out toRemoveMessage);
                        if (toRemoveMessage != null)
                        {
                            toRemoveMessages.Add(toRemoveMessage);
                        }
                    } while (toRemoveMessages.Count < 10 && toRemoveMessage != null);

                    if (toRemoveMessages.Count == 0)
                    {
                        Task.Delay(1000).Wait();
                    }
                    else
                    {
                        using (var scope = ObjectProviderFactory.CreateScope())
                        {
                            var messageStore = scope.GetService <IMessageStore>() as MessageStore;
                            if (messageStore == null)
                            {
                                throw new Exception("invalid messagestore!");
                            }
                            if (messageStore.InMemoryStore)
                            {
                                toRemoveMessages.ForEach(rm =>
                                {
                                    if (rm.Type == MessageType.Command)
                                    {
                                        var removeCommand = messageStore.UnSentCommands.Find(rm.MessageId);
                                        if (removeCommand != null)
                                        {
                                            messageStore.RemoveEntity(removeCommand);
                                        }
                                    }
                                    else if (rm.Type == MessageType.Event)
                                    {
                                        var removeEvent = messageStore.UnPublishedEvents.Find(rm.MessageId);
                                        if (removeEvent != null)
                                        {
                                            messageStore.RemoveEntity(removeEvent);
                                        }
                                    }
                                });
                                messageStore.SaveChanges();
                            }
                            else
                            {
                                var toRemoveCommands = toRemoveMessages.Where(rm => rm.Type == MessageType.Command)
                                                       .Select(rm => rm.MessageId)
                                                       .ToArray();
                                if (toRemoveCommands.Length > 0)
                                {
                                    var deleteCommandsSql = $"delete from msgs_UnSentCommands where Id in ({string.Join(",", toRemoveCommands.Select(rm => $"'{rm}'"))})";
                                    messageStore.Database.ExecuteSqlCommand(deleteCommandsSql);
                                }

                                var toRemoveEvents = toRemoveMessages.Where(rm => rm.Type == MessageType.Event)
                                                     .Select(rm => rm.MessageId)
                                                     .ToArray();
                                if (toRemoveEvents.Length > 0)
                                {
                                    var deleteEventsSql = $"delete from msgs_UnPublishedEvents where Id in ({string.Join(",", toRemoveEvents.Select(rm => $"'{rm}'"))})";
                                    messageStore.Database.ExecuteSqlCommand(deleteEventsSql);
                                }
                            }
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    return;
                }
                catch (ThreadAbortException)
                {
                    return;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"remove Messages Processing faield!");
                }
            }
        }