private StoreQueryService _storeQueryService; //商家 /// <summary> /// IOC 构造函数注入 /// </summary> /// <param name="commandService"></param> /// <param name="conferenceQueryService"></param> public UserController(ICommandService commandService, UserQueryService userQueryService, WalletQueryService walletQueryService, CartQueryService cartQueryService, StoreQueryService storeQueryService) { _commandService = commandService; _userQueryService = userQueryService; _walletQueryService = walletQueryService; _cartQueryService = cartQueryService; _storeQueryService = storeQueryService; }
private StoreQueryService _storeQueryService; //商家 public StatisticsController(ICommandService commandService, UserQueryService userQueryService, WalletQueryService walletQueryService, StoreOrderQueryService storeOrderQueryService, StoreQueryService storeQueryService) { _commandService = commandService; _userQueryService = userQueryService; _walletQueryService = walletQueryService; _storeOrderQueryService = storeOrderQueryService; _storeQueryService = storeQueryService; }
public void ClassLevelSetup() { AutomapperConfiguration.Initialize(); _administrationUnitOfWork = new Mock <IAdministrationUnitOfWork>(); Assert.IsInstanceOf(typeof(IAdministrationUnitOfWork), _administrationUnitOfWork.Object); _identityProvider = new Mock <IServiceIdentityProvider>(); _authorizationPolicy = new Mock <IServiceAuthorizationPolicy>(); _dependencyContainer = new Mock <IDependencyContainer>(); Assert.IsInstanceOf(typeof(IDependencyContainer), _dependencyContainer.Object); _userQueryService = new UserQueryService(_administrationUnitOfWork.Object, Mock.Of <ILog>(), _authorizationPolicy.Object, _identityProvider.Object); Assert.IsInstanceOf(typeof(UserQueryService), _userQueryService); SetUpUser(); SetAgencyPermissions(); }
public AccountController(IOptions <TokenSettings> tokenSettings, AccountService accountSrevice, UserQueryService userQueryService, UserCommandService userCommandService, UserDeviceCommandService userDeviceCommandService, IMapper mapper ) { this.TokenSettings = tokenSettings.Value; this.AccountService = accountSrevice; this.UserQueryService = userQueryService; this.UserCommandService = userCommandService; UserDeviceCommandService = userDeviceCommandService; this.Mapper = mapper; }
public async Task <LoginResult> Login([FromQuery] string email, [FromQuery] string passwordHash, [FromHeader] string token) { var userInfo = UserQueryService.GetUserByEmail(email); if (userInfo == null) { throw new ApiException("User not exists", 500); } if (!string.Equals(passwordHash, userInfo.PasswordHash, StringComparison.OrdinalIgnoreCase)) { throw new ApiException("Authentication Fail, Please confirm your username and password", 500); } return(await GenerateToken(userInfo, true)); }
public async Task UserQuery_Get_Should_Return_Correct_Users() { var queryService = new UserQueryService(new PersistenceContext().ResetDbState()); var users = await queryService.GetAsync(new GetUsersQuery() { Page = 1, PageSize = 5, SearchTerm = "g" }); users.Total.Should().Be(2); users.List.Select(x => x.UserName).ToList().ShouldAllBeEquivalentTo(new List <string>() { Users.GandalfTheAdmin.UserName, Users.Legolas.UserName }); }
//[OutputCache(Duration = 5, VaryByParam = "pageIndex")] public ActionResult Articles(string domain, int?year, int?mouth, int?tag, int?articleTypeId, int?pageIndex) { var user = UserQueryService.GetUserByDomain(domain); var userId = user.ID; var result = _articleQueryService.FindAllPager(userId, articleTypeId, tag, year, mouth, true, pageIndex ?? 1, PageSize); var viewModel = result.Select(CreateArticleViewModel).ToPagedList(pageIndex ?? 1, PageSize, result.TotalCount); ViewData["domain"] = HistoryUser.Domain; #region 如果未登录或者当前用户是当前访问用户 不进行访问信息记录 if (!IsLogin) { return(View("Index", viewModel)); } if (CurrentUser.UserId == HistoryUser.UserId) { return(View("Index", viewModel)); } #endregion // 更新访问信息 try { const int maxCount = 50; using (var transaction = UnitOfWork.Begin()) { _processor.Process <CreateUserTourLogCommand>( new CreateUserTourLogCommand(CurrentUser.UserId, HistoryUser.UserId) { MaxTourUserCount = maxCount }); transaction.Commit(); } } catch (Exception ex) { // 记录日志 LogServer.Error("更新阅读次数失败", ex.Message, HttpContext.Request.Path); } return(View("Index", viewModel)); }
private ApiSession() { //需要配置信息 //从IOC容器中获取queryservice实例 var container = (ObjectContainer.Current as AutofacObjectContainer).Container; _userQueryService = container.Resolve <UserQueryService>(); _walletQueryService = container.Resolve <WalletQueryService>(); _storeQueryService = container.Resolve <StoreQueryService>(); _cartQueryService = container.Resolve <CartQueryService>(); //缓存信息 if (_cache == null) { _cache = CacheFactory.Build("RunTimeCache", settings => { settings.WithSystemRuntimeCacheHandle("inProcessCache") .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(120)); }); } }
static void Main(string[] args) { //-- Poor-man DI - build our dependencies by hand for this demo var dbContextScopeFactory = new DbContextScopeFactory(); var ambientDbContextLocator = new AmbientDbContextLocator(); var userRepository = new UserRepository(ambientDbContextLocator); var userCreationService = new UserCreationService(dbContextScopeFactory, userRepository); var userQueryService = new UserQueryService(dbContextScopeFactory, userRepository); var userEmailService = new UserEmailService(dbContextScopeFactory); var userCreditScoreService = new UserCreditScoreService(dbContextScopeFactory); try { Console.WriteLine("This demo application will create a database named DbContextScopeDemo in the default SQL Server instance on localhost. Edit the connection string in UserManagementDbContext if you'd like to create it somewhere else."); Console.WriteLine("Press enter to start..."); Console.ReadLine(); //-- Demo of typical usage for read and writes Console.WriteLine("Creating a user called Mary..."); var marysSpec = new UserCreationSpec("Mary", "*****@*****.**"); userCreationService.CreateUser(marysSpec); Console.WriteLine("Done.\n"); Console.WriteLine("Trying to retrieve our newly created user from the data store..."); var mary = userQueryService.GetUser(marysSpec.Id); Console.WriteLine("OK. Persisted user: {0}", mary); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of nested DbContextScopes Console.WriteLine("Creating 2 new users called John and Jeanne in an atomic transaction..."); var johnSpec = new UserCreationSpec("John", "*****@*****.**"); var jeanneSpec = new UserCreationSpec("Jeanne", "*****@*****.**"); userCreationService.CreateListOfUsers(johnSpec, jeanneSpec); Console.WriteLine("Done.\n"); Console.WriteLine("Trying to retrieve our newly created users from the data store..."); var createdUsers = userQueryService.GetUsers(johnSpec.Id, jeanneSpec.Id); Console.WriteLine("OK. Found {0} persisted users.", createdUsers.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of nested DbContextScopes in the face of an exception. // If any of the provided users failed to get persisted, none should get persisted. Console.WriteLine("Creating 2 new users called Julie and Marc in an atomic transaction. Will make the persistence of the second user fail intentionally in order to test the atomicity of the transaction..."); var julieSpec = new UserCreationSpec("Julie", "*****@*****.**"); var marcSpec = new UserCreationSpec("Marc", "*****@*****.**"); try { userCreationService.CreateListOfUsersWithIntentionalFailure(julieSpec, marcSpec); Console.WriteLine("Done.\n"); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(); } Console.WriteLine("Trying to retrieve our newly created users from the data store..."); var maybeCreatedUsers = userQueryService.GetUsers(julieSpec.Id, marcSpec.Id); Console.WriteLine("Found {0} persisted users. If this number is 0, we're all good. If this number is not 0, we have a big problem.", maybeCreatedUsers.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of DbContextScope within an async flow Console.WriteLine("Trying to retrieve two users John and Jeanne sequentially in an asynchronous manner..."); // We're going to block on the async task here as we don't have a choice. No risk of deadlocking in any case as console apps // don't have a synchronization context. var usersFoundAsync = userQueryService.GetTwoUsersAsync(johnSpec.Id, jeanneSpec.Id).Result; Console.WriteLine("OK. Found {0} persisted users.", usersFoundAsync.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of explicit database transaction. Console.WriteLine("Trying to retrieve user John within a READ UNCOMMITTED database transaction..."); // You'll want to use SQL Profiler or Entity Framework Profiler to verify that the correct transaction isolation // level is being used. var userMaybeUncommitted = userQueryService.GetUserUncommitted(johnSpec.Id); Console.WriteLine("OK. User found: {0}", userMaybeUncommitted); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of disabling the DbContextScope nesting behaviour in order to force the persistence of changes made to entities // This is a pretty advanced feature that you can safely ignore until you actually need it. Console.WriteLine("Will simulate sending a Welcome email to John..."); using (var parentScope = dbContextScopeFactory.Create()) { var parentDbContext = parentScope.DbContexts.Get <UserManagementDbContext>(); // Load John in the parent DbContext var john = parentDbContext.Users.Find(johnSpec.Id); Console.WriteLine("Before calling SendWelcomeEmail(), john.WelcomeEmailSent = " + john.WelcomeEmailSent); // Now call our SendWelcomeEmail() business logic service method, which will // update John in a non-nested child context userEmailService.SendWelcomeEmail(johnSpec.Id); // Verify that we can see the modifications made to John by the SendWelcomeEmail() method Console.WriteLine("After calling SendWelcomeEmail(), john.WelcomeEmailSent = " + john.WelcomeEmailSent); // Note that even though we're not calling SaveChanges() in the parent scope here, the changes // made to John by SendWelcomeEmail() will remain persisted in the database as SendWelcomeEmail() // forced the creation of a new DbContextScope. } Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demonstration of DbContextScope and parallel programming Console.WriteLine("Calculating and storing the credit score of all users in the database in parallel..."); userCreditScoreService.UpdateCreditScoreForAllUsers(); Console.WriteLine("Done."); } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine(); Console.WriteLine("The end."); Console.WriteLine("Press enter to exit..."); Console.ReadLine(); }
private static void Main(string[] args) { //-- Poor-man DI - build our dependencies by hand for this demo ISessionFactory sessionFactory = UserSessionFactory.CreateSessionFactory(); ISessionScopeFactory sessionScopeFactory = new SessionScopeFactory(sessionFactory); IAmbientSessionLocator ambientSessionLocator = new AmbientSessionLocator(); IUserRepository userRepository = new UserRepository(ambientSessionLocator); var userCreationService = new UserCreationService(sessionScopeFactory, userRepository); var userQueryService = new UserQueryService(sessionScopeFactory, userRepository); var userCreditScoreService = new UserCreditScoreService(sessionScopeFactory); try { Console.WriteLine("This demo application will create a database named NH in the LocalDB SQL Server instance on localhost. Edit the connection string in UserSessionFactory if you'd like to create it somewhere else."); Console.WriteLine("Press enter to start..."); Console.ReadLine(); //-- Demo of typical usage for read and writes Console.WriteLine("Creating a user called Mary..."); var marySpec = new UserCreationSpec("Mary", "*****@*****.**"); userCreationService.CreateUser(marySpec); Console.WriteLine("Done.\n"); Console.WriteLine("Trying to retrieve our newly created user from the data store..."); var mary = userQueryService.GetUser(marySpec.Id); Console.WriteLine("OK. Persisted user: {0}", mary); Console.WriteLine("Trying to retrieve our newly created user from the data store via a repository..."); var maryViaRepo = userQueryService.GetUserViaRepository(marySpec.Id); Console.WriteLine("OK. Persisted user: {0}", maryViaRepo); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of nested SessionScopes Console.WriteLine("Creating 2 new users called John and Jeanne in an atomic transaction..."); var johnSpec = new UserCreationSpec("John", "*****@*****.**"); var jeanneSpec = new UserCreationSpec("Jeanne", "*****@*****.**"); userCreationService.CreateListOfUsers(johnSpec, jeanneSpec); Console.WriteLine("Done.\n"); Console.WriteLine("Trying to retrieve our newly created users from the data store..."); var createdUsers = userQueryService.GetUsers(johnSpec.Id, jeanneSpec.Id); Console.WriteLine("OK. Found {0} persisted users.", createdUsers.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of nested SessionScopes in the face of an exception. // If any of the provided users failed to get persisted, none should get persisted. Console.WriteLine("Creating 2 new users called Julie and Marc in an atomic transaction. Will make the persistence of the second user fail intentionally in order to test the atomicity of the transaction..."); var julieSpec = new UserCreationSpec("Julie", "*****@*****.**"); var marcSpec = new UserCreationSpec("Marc", "*****@*****.**"); try { userCreationService.CreateListOfUsersWithIntentionalFailure(julieSpec, marcSpec); Console.WriteLine("Done.\n"); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(); } Console.WriteLine("Trying to retrieve our newly created users from the data store..."); var maybeCreatedUsers = userQueryService.GetUsers(julieSpec.Id, marcSpec.Id); Console.WriteLine("Found {0} persisted users. If this number is 0, we're all good. If this number is not 0, we have a big problem.", maybeCreatedUsers.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of explicit database transaction isolation level. Console.WriteLine("Trying to retrieve user John within a READ UNCOMMITTED database transaction..."); // You'll want to use SQL Profiler or Entity Framework Profiler to verify that the correct transaction isolation // level is being used. var userMaybeUncommitted = userQueryService.GetUserUncommitted(johnSpec.Id); Console.WriteLine("OK. User found: {0}", userMaybeUncommitted); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demonstration of SessionScope and parallel programming Console.WriteLine("Calculating and storing the credit score of all users in the database in parallel..."); userCreditScoreService.UpdateCreditScoreForAllUsers(); Console.WriteLine("Done."); } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine(); Console.WriteLine("The end."); Console.WriteLine("Press enter to exit..."); Console.ReadLine(); }
public UserController(UserQueryService userQueryService, UserCommandService userCommandService) { this._userQueryService = userQueryService; this._userCommandService = userCommandService; }
public UsersController(UserQueryService userQueryService, UserService userService) { _userQueryService = userQueryService; _userService = userService; }
static void Main(string[] args) { //-- Poor-man DI - build our dependencies by hand for this demo //var dbcontextFactory = new UserManagementDbContextFactory("data source=192.168.0.11;initial catalog=DbContextScopeDemo1;persist security info=True;user id=test;password=111111;MultipleActiveResultSets=True;App=EntityFramework"); var dbcontextFactory = new DbContextFactory("server=127.0.0.1;port=3306;AutoEnlist=true;user id=root;password=jooge2012;persistsecurityinfo=True;database=test;oldguids=True"); var dbContextScopeFactory = new DbContextScopeFactory(dbcontextFactory); var ambientDbContextLocator = new AmbientDbContextLocator(); var userRepository = new UserRepository(ambientDbContextLocator); var userCreationService = new UserCreationService(dbContextScopeFactory, userRepository); var userQueryService = new UserQueryService(dbContextScopeFactory, userRepository); var userEmailService = new UserEmailService(dbContextScopeFactory); var userCreditScoreService = new UserCreditScoreService(dbContextScopeFactory); var userClassService = new UserClassService(dbContextScopeFactory); try { Console.WriteLine("This demo application will create a database named DbContextScopeDemo in the default SQL Server instance on localhost. Edit the connection string in UserManagementDbContext if you'd like to create it somewhere else."); Console.WriteLine("Press enter to start..."); Console.ReadLine(); Console.WriteLine("一个dbScope中使用2个DbContext 创建 a user and userClass Terry+English..."); var user = new User { Id = Guid.NewGuid(), Name = "Terry", Email = "*****@*****.**", WelcomeEmailSent = false, CreatedOn = DateTime.UtcNow }; using (var dbContextScope = dbContextScopeFactory.Create()) { dbContextScope.DbContexts.Get <UserManagementDbContext>().Users.Add(user); userClassService.CreateUserClass(user.Name, "English"); dbContextScope.SaveChanges(); } Console.WriteLine("检查数据库应该有相应的记录user表 和 userClass表"); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); Console.WriteLine("2个dbcontext 使用事务的情况,"); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); user = new User { Id = Guid.NewGuid(), Name = "Mark", Email = "*****@*****.**", WelcomeEmailSent = false, CreatedOn = DateTime.UtcNow }; int rowCount = 0; try { using (var s = new TransactionScope()) { using (var dbContextScope = dbContextScopeFactory.Create()) { dbContextScope.DbContexts.Get <UserManagementDbContext>().Users.Add(user); dbContextScope.SaveChanges(); } rowCount = userClassService.GetRowCount(); userClassService.CreateUserClass(user.Name, "English"); throw new Exception("模拟错误"); s.Complete(); } } catch { } var tempUsers = userQueryService.GetUsers(user.Id); Console.WriteLine("Found {0} persisted users. If this number is 0, we're all good. If this number is not 0, we have a big problem.", tempUsers.Count()); if (rowCount == userClassService.GetRowCount()) { Console.WriteLine("userClass表的数量没有变化,是正确的,如果变化了就不对了"); } else { Console.WriteLine("userClass表的数量变化了,是不对的。"); } //-- Demo of typical usage for read and writes Console.WriteLine("Creating a user called Mary..."); var marysSpec = new UserCreationSpec("Mary", "*****@*****.**"); userCreationService.CreateUser(marysSpec); Console.WriteLine("Done.\n"); Console.WriteLine("Trying to retrieve our newly created user from the data store..."); var mary = userQueryService.GetUser(marysSpec.Id); Console.WriteLine("OK. Persisted user: {0}", mary); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of nested DbContextScopes Console.WriteLine("Creating 2 new users called John and Jeanne in an atomic transaction..."); var johnSpec = new UserCreationSpec("John", "*****@*****.**"); var jeanneSpec = new UserCreationSpec("Jeanne", "*****@*****.**"); userCreationService.CreateListOfUsers(johnSpec, jeanneSpec); Console.WriteLine("Done.\n"); Console.WriteLine("Trying to retrieve our newly created users from the data store..."); var createdUsers = userQueryService.GetUsers(johnSpec.Id, jeanneSpec.Id); Console.WriteLine("OK. Found {0} persisted users.", createdUsers.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of nested DbContextScopes in the face of an exception. // If any of the provided users failed to get persisted, none should get persisted. Console.WriteLine("Creating 2 new users called Julie and Marc in an atomic transaction. Will make the persistence of the second user fail intentionally in order to test the atomicity of the transaction..."); var julieSpec = new UserCreationSpec("Julie", "*****@*****.**"); var marcSpec = new UserCreationSpec("Marc", "*****@*****.**"); try { userCreationService.CreateListOfUsersWithIntentionalFailure(julieSpec, marcSpec); Console.WriteLine("Done.\n"); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(); } Console.WriteLine("Trying to retrieve our newly created users from the data store..."); var maybeCreatedUsers = userQueryService.GetUsers(julieSpec.Id, marcSpec.Id); Console.WriteLine("Found {0} persisted users. If this number is 0, we're all good. If this number is not 0, we have a big problem.", maybeCreatedUsers.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of DbContextScope within an async flow Console.WriteLine("Trying to retrieve two users John and Jeanne sequentially in an asynchronous manner..."); // We're going to block on the async task here as we don't have a choice. No risk of deadlocking in any case as console apps // don't have a synchronization context. var usersFoundAsync = userQueryService.GetTwoUsersAsync(johnSpec.Id, jeanneSpec.Id).Result; Console.WriteLine("OK. Found {0} persisted users.", usersFoundAsync.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of explicit database transaction. Console.WriteLine("Trying to retrieve user John within a READ UNCOMMITTED database transaction..."); // You'll want to use SQL Profiler or Entity Framework Profiler to verify that the correct transaction isolation // level is being used. var userMaybeUncommitted = userQueryService.GetUserUncommitted(johnSpec.Id); Console.WriteLine("OK. User found: {0}", userMaybeUncommitted); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of disabling the DbContextScope nesting behaviour in order to force the persistence of changes made to entities // This is a pretty advanced feature that you can safely ignore until you actually need it. Console.WriteLine("Will simulate sending a Welcome email to John..."); using (var parentScope = dbContextScopeFactory.Create()) { var parentDbContext = parentScope.DbContexts.Get <UserManagementDbContext>(); // Load John in the parent DbContext var john = parentDbContext.Users.Find(johnSpec.Id); Console.WriteLine("Before calling SendWelcomeEmail(), john.WelcomeEmailSent = " + john.WelcomeEmailSent); // Now call our SendWelcomeEmail() business logic service method, which will // update John in a non-nested child context userEmailService.SendWelcomeEmail(johnSpec.Id); // Verify that we can see the modifications made to John by the SendWelcomeEmail() method Console.WriteLine("After calling SendWelcomeEmail(), john.WelcomeEmailSent = " + john.WelcomeEmailSent); // Note that even though we're not calling SaveChanges() in the parent scope here, the changes // made to John by SendWelcomeEmail() will remain persisted in the database as SendWelcomeEmail() // forced the creation of a new DbContextScope. } Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demonstration of DbContextScope and parallel programming Console.WriteLine("Calculating and storing the credit score of all users in the database in parallel..."); userCreditScoreService.UpdateCreditScoreForAllUsers(); Console.WriteLine("Done."); Console.WriteLine("Trying to retrieve users by where clause."); var users = userQueryService.GetUserByWhereClause(" WelcomeEmailSent = 1 "); Console.WriteLine("OK. WelcomeEmailSent user count: {0}", users.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine(); Console.WriteLine("The end."); Console.WriteLine("Press enter to exit..."); Console.ReadLine(); }
static void Main(string[] args) { //-- Poor-man DI - build our dependencies by hand for this demo IDbScopeFactory dbScopeFactory = new EntityFrameworkScopeFactory(); IAmbientDbLocator ambientDbLocator = new EntityFrameworkAmbientLocator(); IUserRepository userRepository = new UserRepository(ambientDbLocator); var userCreationService = new UserCreationService(dbScopeFactory, userRepository); var userQueryService = new UserQueryService(dbScopeFactory, userRepository); var userEmailService = new UserEmailService(dbScopeFactory); var userCreditScoreService = new UserCreditScoreService(dbScopeFactory); try { Console.WriteLine("This demo application will create a database named DbContextScopeDemo in the default SQL Server instance on localhost. Edit the connection string in UserManagementDbContext if you'd like to create it somewhere else."); Console.WriteLine("Press enter to start..."); Console.ReadLine(); //-- Demo of typical usage for read and writes Console.WriteLine("Creating a user called Mary..."); var marysSpec = new UserCreationSpec("Mary", "*****@*****.**"); userCreationService.CreateUser(marysSpec); Console.WriteLine("Done.\n"); Console.WriteLine("Trying to retrieve our newly created user from the data store..."); var mary = userQueryService.GetUser(marysSpec.Id); Console.WriteLine("OK. Persisted user: {0}", mary); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of nested DbScopes Console.WriteLine("Creating 2 new users called John and Jeanne in an atomic transaction..."); var johnSpec = new UserCreationSpec("John", "*****@*****.**"); var jeanneSpec = new UserCreationSpec("Jeanne", "*****@*****.**"); userCreationService.CreateListOfUsers(johnSpec, jeanneSpec); Console.WriteLine("Done.\n"); Console.WriteLine("Trying to retrieve our newly created users from the data store..."); var createdUsers = userQueryService.GetUsers(johnSpec.Id, jeanneSpec.Id); Console.WriteLine("OK. Found {0} persisted users.", createdUsers.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of nested DbScopes in the face of an exception. // If any of the provided users failed to get persisted, none should get persisted. Console.WriteLine("Creating 2 new users called Julie and Marc in an atomic transaction. Will make the persistence of the second user fail intentionally in order to test the atomicity of the transaction..."); var julieSpec = new UserCreationSpec("Julie", "*****@*****.**"); var marcSpec = new UserCreationSpec("Marc", "*****@*****.**"); try { userCreationService.CreateListOfUsersWithIntentionalFailure(julieSpec, marcSpec); Console.WriteLine("Done.\n"); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(); } Console.WriteLine("Trying to retrieve our newly created users from the data store..."); var maybeCreatedUsers = userQueryService.GetUsers(julieSpec.Id, marcSpec.Id); Console.WriteLine("Found {0} persisted users. If this number is 0, we're all good. If this number is not 0, we have a big problem.", maybeCreatedUsers.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of DbScope within an async flow Console.WriteLine("Trying to retrieve two users John and Jeanne sequentially in an asynchronous manner..."); // We're going to block on the async task here as we don't have a choice. No risk of deadlocking in any case as console apps // don't have a synchronization context. var usersFoundAsync = userQueryService.GetTwoUsersAsync(johnSpec.Id, jeanneSpec.Id).Result; Console.WriteLine("OK. Found {0} persisted users.", usersFoundAsync.Count()); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of explicit database transaction. Console.WriteLine("Trying to retrieve user John within a READ UNCOMMITTED database transaction..."); // You'll want to use SQL Profiler or Entity Framework Profiler to verify that the correct transaction isolation // level is being used. var userMaybeUncommitted = userQueryService.GetUserUncommitted(johnSpec.Id); Console.WriteLine("OK. User found: {0}", userMaybeUncommitted); Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demo of disabling the DbScope nesting behaviour in order to force the persistence of changes made to entities // This is a pretty advanced feature that you can safely ignore until you actually need it. Console.WriteLine("Will simulate sending a Welcome email to John..."); using (var parentScope = dbScopeFactory.Create()) { var parentDbContext = parentScope.Get<UserManagementDbContext>(); // Load John in the parent DbContext var john = parentDbContext.Users.Find(johnSpec.Id); Console.WriteLine("Before calling SendWelcomeEmail(), john.WelcomeEmailSent = " + john.WelcomeEmailSent); // Now call our SendWelcomeEmail() business logic service method, which will // update John in a non-nested child context userEmailService.SendWelcomeEmail(johnSpec.Id); // Verify that we can see the modifications made to John by the SendWelcomeEmail() method Console.WriteLine("After calling SendWelcomeEmail(), john.WelcomeEmailSent = " + john.WelcomeEmailSent); // Note that even though we're not calling SaveChanges() in the parent scope here, the changes // made to John by SendWelcomeEmail() will remain persisted in the database as SendWelcomeEmail() // forced the creation of a new DbScope. } Console.WriteLine("Press enter to continue..."); Console.ReadLine(); //-- Demonstration of DbScope and parallel programming Console.WriteLine("Calculating and storing the credit score of all users in the database in parallel..."); userCreditScoreService.UpdateCreditScoreForAllUsers(); Console.WriteLine("Done."); } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine(); Console.WriteLine("The end."); Console.WriteLine("Press enter to exit..."); Console.ReadLine(); }