예제 #1
0
        public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails()
        {
            var user = new IdentityUser("test");
            var httpContext = new Mock<HttpContext>();
            var userManager = MockHelpers.MockUserManager<IdentityUser>();
            var authManager = new Mock<IAuthenticationManager>();
            var claimsManager = new Mock<IClaimsIdentityFactory<IdentityUser>>();
            var signInManager = new Mock<SignInManager<IdentityUser>>(userManager.Object,
                authManager.Object, claimsManager.Object);
            signInManager.Setup(s => s.ValidateSecurityStamp(It.IsAny<ClaimsIdentity>(), user.Id)).ReturnsAsync(null).Verifiable();
            var services = new ServiceCollection();
            services.AddInstance(signInManager.Object);
            httpContext.Setup(c => c.ApplicationServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(ClaimsIdentityOptions.DefaultAuthenticationType);
            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow });
            var context = new CookieValidateIdentityContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Identity);
            await
                SecurityStampValidator.OnValidateIdentity<IdentityUser>(TimeSpan.Zero).Invoke(context);
            Assert.Null(context.Identity);
            signInManager.VerifyAll();
        }
        private async Task Can_use_connection_string_name_in_OnConfiguring_test(string connectionName)
        {
            var configuration = new Configuration
                {
                    new MemoryConfigurationSource(
                        new Dictionary<string, string>
                            {
                                { "Data:Northwind:ConnectionString", SqlServerTestDatabase.NorthwindConnectionString }
                            })
                };

            var serviceCollection = new ServiceCollection();
            serviceCollection
                .AddInstance<IConfiguration>(configuration)
                .AddEntityFramework()
                .AddSqlServer();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            using (await SqlServerTestDatabase.Northwind())
            {
                using (var context = new NorthwindContext(serviceProvider, connectionName))
                {
                    Assert.Equal(91, await context.Customers.CountAsync());
                }
            }
        }
        public void AddWebEncoders_DoesNotOverrideExistingRegisteredEncoders()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();

            // Act
            serviceCollection.AddSingleton<IHtmlEncoder, CommonTestEncoder>();
            serviceCollection.AddSingleton<IJavaScriptStringEncoder, CommonTestEncoder>();
            // we don't register an existing URL encoder
            serviceCollection.AddWebEncoders(options =>
            {
                options.CodePointFilter = new CodePointFilter().AllowChars("ace"); // only these three chars are allowed
            });

            // Assert
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var htmlEncoder = serviceProvider.GetHtmlEncoder();
            Assert.Equal("HtmlEncode[[abcde]]", htmlEncoder.HtmlEncode("abcde"));

            var javaScriptStringEncoder = serviceProvider.GetJavaScriptStringEncoder();
            Assert.Equal("JavaScriptStringEncode[[abcde]]", javaScriptStringEncoder.JavaScriptStringEncode("abcde"));

            var urlEncoder = serviceProvider.GetUrlEncoder();
            Assert.Equal("a%62c%64e", urlEncoder.UrlEncode("abcde"));
        }
        public void AddWebEncoders_WithOptions_RegistersEncodersWithCustomCodeFilter()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();

            // Act
            serviceCollection.AddWebEncoders(options =>
            {
                options.CodePointFilter = new CodePointFilter().AllowChars("ace"); // only these three chars are allowed
            });

            // Assert
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var htmlEncoder = serviceProvider.GetRequiredService<IHtmlEncoder>();
            Assert.Equal("a&#x62;c&#x64;e", htmlEncoder.HtmlEncode("abcde"));
            Assert.Same(htmlEncoder, serviceProvider.GetRequiredService<IHtmlEncoder>()); // as singleton instance

            var javaScriptStringEncoder = serviceProvider.GetRequiredService<IJavaScriptStringEncoder>();
            Assert.Equal(@"a\u0062c\u0064e", javaScriptStringEncoder.JavaScriptStringEncode("abcde"));
            Assert.Same(javaScriptStringEncoder, serviceProvider.GetRequiredService<IJavaScriptStringEncoder>()); // as singleton instance

            var urlEncoder = serviceProvider.GetRequiredService<IUrlEncoder>();
            Assert.Equal("a%62c%64e", urlEncoder.UrlEncode("abcde"));
            Assert.Same(urlEncoder, serviceProvider.GetRequiredService<IUrlEncoder>()); // as singleton instance
        }
예제 #5
0
        public void Main(string[] args)
        {
            var services = new ServiceCollection();

            services
                .AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<UserDbContext>()
                .AddEntityFrameworkMixins();

            var provider = services.BuildServiceProvider();
            var context = provider.GetRequiredService<UserDbContext>();

            var users = (
                from u in context.Users
                where u.Mixin<Author>().GooglePlusProfile != null
                select u //u.Mixin<Author>()
            ).ToList();

            var user = users.FirstOrDefault();
            if (user != null)
            {
                var author = user.Mixin<Author>();

                // You can make changes here:
                author.IsAwesome = true;

                // Save changes
                context.SaveChanges();
            }
        }
예제 #6
0
        public async Task CanIncludeUserClaimsTest()
        {
            // Arrange
            CreateContext(true);
            var builder = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider);

            var services = new ServiceCollection();
            DbUtil.ConfigureDbServices<IdentityDbContext>(ConnectionString, services);
            services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
            builder.ApplicationServices = services.BuildServiceProvider();

            var userManager = builder.ApplicationServices.GetRequiredService<UserManager<IdentityUser>>();
            var dbContext = builder.ApplicationServices.GetRequiredService<IdentityDbContext>();

            var username = "******" + new Random().Next();
            var user = new IdentityUser() { UserName = username };
            IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user));

            for (var i = 0; i < 10; i++)
            {
                IdentityResultAssert.IsSuccess(await userManager.AddClaimAsync(user, new Claim(i.ToString(), "foo")));
            }

            user = dbContext.Users.Include(x => x.Claims).FirstOrDefault(x => x.UserName == username);

            // Assert
            Assert.NotNull(user);
            Assert.NotNull(user.Claims);
            Assert.Equal(10, user.Claims.Count());
        }
예제 #7
0
        public void ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName()
        {
            // Arrange
            var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = metadataProvider.GetMetadataForProperty(typeof(PropertyDisplayNameModel), "MyProperty");

            var attribute = new CompareAttribute("OtherProperty");
            var adapter = new CompareAttributeAdapter(attribute);

            var serviceCollection = new ServiceCollection();
            var requestServices = serviceCollection.BuildServiceProvider();

            var context = new ClientModelValidationContext(metadata, metadataProvider, requestServices);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent(
                    "'MyPropertyDisplayName' and 'OtherPropertyDisplayName' do not match."),
                rule.ErrorMessage);
        }
예제 #8
0
        public void json_collection_with_default_culture_test()
        {
            // Arrange
            var req = new Mock<HttpRequest>();
            req.Setup(x => x.Headers)
                .Returns(new HeaderDictionary(new Dictionary<string, StringValues> { }));
            req.Setup(x => x.Cookies)
                .Returns(new RequestCookiesCollection());
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(x => x.Request)
                .Returns(req.Object);
            var accessor = new Mock<IHttpContextAccessor>();
            accessor.Setup(x => x.HttpContext)
                .Returns(httpContext.Object);

            var collection = new ServiceCollection();
            collection.AddJsonLocalization()
                .AddCookieCulture()
                .AddInstance(accessor.Object)
                .AddInstance(CallContextServiceLocator.Locator.ServiceProvider.GetRequiredService<IApplicationEnvironment>());

            var service = collection.BuildServiceProvider();

            // Act
            var SR = service.GetService<ILocalizationStringCollection>();
            var actual_1 = SR["Hello world."];
            var actual_2 = SR["My name is {0}.", "Yuuko"];

            // Assert
            Assert.Equal("你好,世界。", actual_1);
            Assert.Equal("我的名字是Yuuko", actual_2);
        }
예제 #9
0
        public Task<int> Main(string[] args)
        {
            //Add command line configuration source to read command line parameters.
            var config = new Configuration();
            config.AddCommandLine(args);

            var serviceCollection = new ServiceCollection();
            serviceCollection.Add(HostingServices.GetDefaultServices(config));
            var services = serviceCollection.BuildServiceProvider(_hostServiceProvider);

            var context = new HostingContext()
            {
                Services = services,
                Configuration = config,
                ServerName = "Microsoft.AspNet.Server.WebListener",
                ApplicationName = "BugTracker"
            };

            var engine = services.GetService<IHostingEngine>();
            if (engine == null)
            {
                throw new Exception("TODO: IHostingEngine service not available exception");
            }

            using (engine.Start(context))
            {
                Console.WriteLine("Started the server..");
                Console.WriteLine("Press any key to stop the server");
                Console.ReadLine();
            }
            return Task.FromResult(0);
        }
        public void GetKeyEscrowSink_MultipleKeyEscrowRegistration_ReturnsAggregate()
        {
            // Arrange
            List<string> output = new List<string>();

            var mockKeyEscrowSink1 = new Mock<IKeyEscrowSink>();
            mockKeyEscrowSink1.Setup(o => o.Store(It.IsAny<Guid>(), It.IsAny<XElement>()))
                .Callback<Guid, XElement>((keyId, element) =>
                {
                    output.Add(String.Format(CultureInfo.InvariantCulture, "[sink1] {0:D}: {1}", keyId, element.Name.LocalName));
                });

            var mockKeyEscrowSink2 = new Mock<IKeyEscrowSink>();
            mockKeyEscrowSink2.Setup(o => o.Store(It.IsAny<Guid>(), It.IsAny<XElement>()))
                .Callback<Guid, XElement>((keyId, element) =>
                {
                    output.Add(String.Format(CultureInfo.InvariantCulture, "[sink2] {0:D}: {1}", keyId, element.Name.LocalName));
                });

            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<IKeyEscrowSink>(mockKeyEscrowSink1.Object);
            serviceCollection.AddInstance<IKeyEscrowSink>(mockKeyEscrowSink2.Object);
            var services = serviceCollection.BuildServiceProvider();

            // Act
            var sink = services.GetKeyEscrowSink();
            sink.Store(new Guid("39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b"), XElement.Parse("<theElement />"));

            // Assert
            Assert.Equal(new[] { "[sink1] 39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b: theElement", "[sink2] 39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b: theElement" }, output);
        }
        public void Activate_InitializesTagHelpersWithMultipleInitializers()
        {
            // Arrange
            var services = new ServiceCollection();
            services.InitializeTagHelper<TestTagHelper>((h, vc) =>
            {
                h.Name = "Test 1";
                h.Number = 100;
            });
            services.InitializeTagHelper<TestTagHelper>((h, vc) =>
            {
                h.Name += ", Test 2";
                h.Number += 100;
            });
            var httpContext = MakeHttpContext(services.BuildServiceProvider());
            var viewContext = MakeViewContext(httpContext);
            var activator = new DefaultTagHelperActivator();
            var helper = new TestTagHelper();

            // Act
            activator.Activate(helper, viewContext);

            // Assert
            Assert.Equal("Test 1, Test 2", helper.Name);
            Assert.Equal(200, helper.Number);
        }
        public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
        {
            var user = new TestUser("test");
            var userManager = MockHelpers.MockUserManager<TestUser>();
            var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
            var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero };
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Options).Returns(identityOptions);
            var httpContext = new Mock<HttpContext>();
            var contextAccessor = new Mock<IHttpContextAccessor>();
            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object,
                contextAccessor.Object, claimsManager.Object, options.Object, null);
            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(user).Verifiable();
            signInManager.Setup(s => s.SignInAsync(user, isPersistent, null)).Returns(Task.FromResult(0)).Verifiable();
            var services = new ServiceCollection();
            services.AddInstance(options.Object);
            services.AddInstance(signInManager.Object);
            services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>());
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme);
            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(id), 
                new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow, IsPersistent = isPersistent }, 
                IdentityOptions.ApplicationCookieAuthenticationScheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Principal);
            await
                SecurityStampValidator.ValidatePrincipalAsync(context);
            Assert.NotNull(context.Principal);
            signInManager.VerifyAll();
        }
예제 #13
0
        // Composition root
        private IServiceProvider BuildServiceProvider(Options options, IConfigurationSection queueConfig)
        {
            var services = new ServiceCollection().AddLogging();

            services.AddSingleton<IMessageHandlerFactory, MessageHandlerFactory>();

            switch (options.QueueType)
            {
                case "zeromq":
                    services.AddZeroMq(queueConfig);
                    break;
                case "msmq":
                    services.AddMsmq(queueConfig);
                    break;
                case "azure":
                    services.AddAzure(queueConfig);
                    break;
                default:
                    throw new Exception($"Could not resolve queue type {options.QueueType}");
            }

            if (!string.IsNullOrWhiteSpace(options.Handler))
            {
                services.AddTransient(typeof(IMessageHandler), Type.GetType(options.Handler));
            }

            var provider = services.BuildServiceProvider();

            // configure
            var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
            loggerFactory.MinimumLevel = LogLevel.Debug;
            loggerFactory.AddConsole(loggerFactory.MinimumLevel);

            return provider;
        }
예제 #14
0
파일: Program.cs 프로젝트: beginor/practice
        public void Main(string[] args) {
            var connectionString = @"Data Source=(localdb)\mssqllocaldb;Initial Catalog=Test;Integrated Security=True;Connect Timeout=30;";
            IServiceCollection services = new ServiceCollection();
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<DataContext>(options => options.UseSqlServer(connectionString));

            var serviceProvider = services.BuildServiceProvider();
            //serviceProvider.Add
            
            var context = serviceProvider.GetService<DataContext>();

            var categoryCount = context.Categories.Count();
            Console.WriteLine($"category count is {categoryCount}");

            var newCat = new Category {
                Name = $"Category {categoryCount + 1}",
                Description = $"Category {categoryCount + 1} description"
            };
            context.Add(newCat);
            //context.SaveChanges();
            var count = context.SaveChanges();
            Console.WriteLine($"change count is {count}");
            context.Dispose();
            Console.WriteLine("Hello, world!");
        }
예제 #15
0
 public static RoleManager<IdentityRole> CreateRoleManager(InMemoryContext context)
 {
     var services = new ServiceCollection();
     services.AddIdentity<IdentityUser, IdentityRole>();
     services.AddInstance<IRoleStore<IdentityRole>>(new RoleStore<IdentityRole>(context));
     return services.BuildServiceProvider().GetRequiredService<RoleManager<IdentityRole>>();
 }
        public void ClientRulesWithMaxLengthAttribute_StringLocalizer_ReturnsLocalizedErrorString()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");
            var errorKey = metadata.GetDisplayName();
            var attribute = new MaxLengthAttribute(10);
            attribute.ErrorMessage = errorKey;

            var localizedString = new LocalizedString(errorKey, "Longueur est invalide");
            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s[errorKey]).Returns(localizedString);

            var adapter = new MaxLengthAttributeAdapter(attribute, stringLocalizer.Object);
            var serviceCollection = new ServiceCollection();
            var requestServices = serviceCollection.BuildServiceProvider();
            var context = new ClientModelValidationContext(metadata, provider, requestServices);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("maxlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(10, rule.ValidationParameters["max"]);
            Assert.Equal("Longueur est invalide", rule.ErrorMessage);
        }
예제 #17
0
        public void TestHelloNonGenericServiceDecoratorNoInterface()
        {
            var services = new ServiceCollection();

            services.AddInstance<IHelloService>(new HelloService());

            services.AddSingleton<IHelloService>(sp => new HelloService());
            services.AddScoped<IHelloService>(sp => new HelloService());
            services.AddTransient<IHelloService>(sp => new HelloService());

            services.AddSingleton<IHelloService, HelloService>();
            services.AddScoped<IHelloService, HelloService>();
            services.AddTransient<IHelloService, HelloService>();

            services.AddDecorator(typeof(IHelloService), (sp, s) => new HelloServiceDecoratorNoInterface((IHelloService)s));

            var provider = services.BuildServiceProvider();

            var helloServices = provider.GetRequiredServices<IHelloService>();
            Assert.NotNull(helloServices);
            var collection = helloServices as IHelloService[] ?? helloServices.ToArray();
            Assert.Equal(7, collection.Length);
            Assert.NotEmpty(collection);
            foreach (var helloService in collection)
            {
                Assert.NotNull(helloService);
                Assert.Equal("Decorated without interface: Hello world.", helloService.SayHello("world"));
            }
        }
예제 #18
0
파일: Startup.cs 프로젝트: SharpStar/Star2
        public void ConfigureServices()
        {
            IServiceProvider mainProv = CallContextServiceLocator.Locator.ServiceProvider;
            IApplicationEnvironment appEnv = mainProv.GetService<IApplicationEnvironment>();
            IRuntimeEnvironment runtimeEnv = mainProv.GetService<IRuntimeEnvironment>();

            ILoggerFactory logFactory = new LoggerFactory();
            logFactory.AddConsole(LogLevel.Information);

            ServiceCollection sc = new ServiceCollection();
            sc.AddInstance(logFactory);
            sc.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
            sc.AddEntityFramework()
                .AddSqlite()
                .AddDbContext<StarDbContext>();

            sc.AddSingleton<ILibraryManager, LibraryManager>(factory => mainProv.GetService<ILibraryManager>() as LibraryManager);
            sc.AddSingleton<ICache, Cache>(factory => new Cache(new CacheContextAccessor()));
            sc.AddSingleton<IExtensionAssemblyLoader, ExtensionAssemblyLoader>();
            sc.AddSingleton<IStarLibraryManager, StarLibraryManager>();
            sc.AddSingleton<PluginLoader>();
            sc.AddSingleton(factory => mainProv.GetService<IAssemblyLoadContextAccessor>());
            sc.AddInstance(appEnv);
            sc.AddInstance(runtimeEnv);

            Services = sc;

            ServiceProvider = sc.BuildServiceProvider();
        }
예제 #19
0
 /// <summary>
 /// This follows the same initialization that is provided when <see cref="IDataProtectionProvider"/>
 /// is initialized within ASP.NET 5.0 Dependency Injection.
 /// </summary>
 /// <returns>A fully initialized <see cref="IDataProtectionProvider"/>.</returns>
 internal static IDataProtectionProvider GetDataProtectionProvider()
 {
     ServiceCollection serviceCollection = new ServiceCollection();
     serviceCollection.AddDataProtection();
     IServiceProvider services = serviceCollection.BuildServiceProvider();
     return services.GetDataProtectionProvider();
 }
        public ActivityApiControllerTest()
        {
            if (_serviceProvider == null)
            {
                var services = new ServiceCollection();

                // Add Configuration to the Container
                var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddEnvironmentVariables();
                IConfiguration configuration = builder.Build();
                services.AddSingleton(x => configuration);

                // Add EF (Full DB, not In-Memory)
                services.AddEntityFramework()
                    .AddInMemoryDatabase()
                    .AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase());

                // Setup hosting environment
                IHostingEnvironment hostingEnvironment = new HostingEnvironment();
                hostingEnvironment.EnvironmentName = "Development";
                services.AddSingleton(x => hostingEnvironment);
                _serviceProvider = services.BuildServiceProvider();
            }
        }
        public void Activate_InitializesTagHelpers(string name, int number)
        {
            // Arrange
            var services = new ServiceCollection();
            services.InitializeTagHelper<TestTagHelper>((h, vc) =>
            {
                h.Name = name;
                h.Number = number;
                h.ViewDataValue = vc.ViewData["TestData"];
            });
            var httpContext = MakeHttpContext(services.BuildServiceProvider());
            var viewContext = MakeViewContext(httpContext);
            var viewDataValue = new object();
            viewContext.ViewData.Add("TestData", viewDataValue);
            var activator = new DefaultTagHelperActivator();
            var helper = new TestTagHelper();

            // Act
            activator.Activate(helper, viewContext);

            // Assert
            Assert.Equal(name, helper.Name);
            Assert.Equal(number, helper.Number);
            Assert.Same(viewDataValue, helper.ViewDataValue);
        }
        public static HttpContextAccessor CreateHttpContextAccessor(RequestTelemetry requestTelemetry = null, ActionContext actionContext = null)
        {
            var services = new ServiceCollection();

            var request = new DefaultHttpContext().Request;
            request.Method = "GET";
            request.Path = new PathString("/Test");
            var contextAccessor = new HttpContextAccessor() { HttpContext = request.HttpContext };

            services.AddInstance<IHttpContextAccessor>(contextAccessor);

            if (actionContext != null)
            {
                var si = new ActionContextAccessor();
                si.ActionContext = actionContext;
                services.AddInstance<IActionContextAccessor>(si);
            }

            if (requestTelemetry != null)
            {
                services.AddInstance<RequestTelemetry>(requestTelemetry);
            }

            IServiceProvider serviceProvider = services.BuildServiceProvider();
            contextAccessor.HttpContext.RequestServices = serviceProvider;

            return contextAccessor;
        }
        private static async Task Can_use_an_existing_closed_connection_test(bool openConnection)
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection
                .AddEntityFramework()
                .AddSqlServer();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            using (var store = await SqlServerNorthwindContext.GetSharedStoreAsync())
            {
                var openCount = 0;
                var closeCount = 0;
                var disposeCount = 0;

                using (var connection = new SqlConnection(store.Connection.ConnectionString))
                {
                    if (openConnection)
                    {
                        await connection.OpenAsync();
                    }

                    connection.StateChange += (_, a) =>
                        {
                            if (a.CurrentState == ConnectionState.Open)
                            {
                                openCount++;
                            }
                            else if (a.CurrentState == ConnectionState.Closed)
                            {
                                closeCount++;
                            }
                        };
#if !DNXCORE50
                    connection.Disposed += (_, __) => disposeCount++;
#endif

                    using (var context = new NorthwindContext(serviceProvider, connection))
                    {
                        Assert.Equal(91, await context.Customers.CountAsync());
                    }

                    if (openConnection)
                    {
                        Assert.Equal(ConnectionState.Open, connection.State);
                        Assert.Equal(0, openCount);
                        Assert.Equal(0, closeCount);
                    }
                    else
                    {
                        Assert.Equal(ConnectionState.Closed, connection.State);
                        Assert.Equal(1, openCount);
                        Assert.Equal(1, closeCount);
                    }

                    Assert.Equal(0, disposeCount);
                }
            }
        }
예제 #24
0
            public Task Invoke(HttpContext httpContext)
            {
                var services = new ServiceCollection();
                services.AddTransient<TestService>();
                httpContext.RequestServices = services.BuildServiceProvider();

                return _next.Invoke(httpContext);
            }
예제 #25
0
 private IServiceProvider ConfigureServices()
 {
     var services = new ServiceCollection();
     DbUtil.ConfigureDbServices<IdentityDbContext>(ConnectionString, services);
     services.AddLogging();
     services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
     return services.BuildServiceProvider();
 }
예제 #26
0
        public static IServiceProvider Build()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddScoped<IAppDataDirectory, AppDataDirectory>();
            serviceCollection.AddScoped<IRootDirectory, RootDirectory>();

            return serviceCollection.BuildServiceProvider();
        }
 public static DbContextConfiguration CreateConfiguration()
 {
     var serviceCollection = new ServiceCollection();
     serviceCollection.AddEntityFramework().AddSqlServer();
     return new DbContext(serviceCollection.BuildServiceProvider(),
         new DbContextOptions()
             .UseSqlServer("Server=(localdb)\v11.0;Database=SqlServerConnectionTest;Trusted_Connection=True;"))
         .Configuration;
 }
예제 #28
0
        public GenreMenuComponentTest()
        {
            var services = new ServiceCollection();
            services.AddEntityFramework()
                      .AddInMemoryStore()
                      .AddDbContext<MusicStoreContext>();

            _serviceProvider = services.BuildServiceProvider();
        }
        public static IServiceProvider CreateServiceProvider(Action<IServiceCollection> configure)
        {
            var collection = new ServiceCollection()
                .AddMessageBus()
                .AddSingleton<ILoggerFactory, LoggerFactory>();

            configure(collection);

            return collection.BuildServiceProvider();
        }
        public CartSummaryComponentTest()
        {
            var services = new ServiceCollection();

            services.AddEntityFramework()
                      .AddInMemoryDatabase()
                      .AddDbContext<MusicStoreContext>(options => options.UseInMemoryDatabase());

            _serviceProvider = services.BuildServiceProvider();
        }