diff --git a/src/Microsoft.EntityFrameworkCore.Commands/Properties/CommandsStrings.Designer.cs b/src/Microsoft.EntityFrameworkCore.Commands/Properties/CommandsStrings.Designer.cs index 32f84557f75..23da169335c 100644 --- a/src/Microsoft.EntityFrameworkCore.Commands/Properties/CommandsStrings.Designer.cs +++ b/src/Microsoft.EntityFrameworkCore.Commands/Properties/CommandsStrings.Designer.cs @@ -301,7 +301,7 @@ public static string RootNamespaceRequired } /// - /// Your target project '{assembly}' doesn't match your migrations assembly '{migrationsAssembly}'. Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list or by using the '--targetProject' option for DNX commands. Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer().MigrationsAssembly("{assembly}") + /// Your target project '{assembly}' doesn't match your migrations assembly '{migrationsAssembly}'. Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list or by using the '--targetProject' option for DNX commands. Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("{assembly}")) /// public static string MigrationsAssemblyMismatch([CanBeNull] object assembly, [CanBeNull] object migrationsAssembly) { diff --git a/src/Microsoft.EntityFrameworkCore.Commands/Properties/CommandsStrings.resx b/src/Microsoft.EntityFrameworkCore.Commands/Properties/CommandsStrings.resx index 8e443850920..7c1e6189f3f 100644 --- a/src/Microsoft.EntityFrameworkCore.Commands/Properties/CommandsStrings.resx +++ b/src/Microsoft.EntityFrameworkCore.Commands/Properties/CommandsStrings.resx @@ -226,7 +226,7 @@ Root namespace of the project is required to generate code. - Your target project '{assembly}' doesn't match your migrations assembly '{migrationsAssembly}'. Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list or by using the '--targetProject' option for DNX commands. Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer().MigrationsAssembly("{assembly}") + Your target project '{assembly}' doesn't match your migrations assembly '{migrationsAssembly}'. Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list or by using the '--targetProject' option for DNX commands. Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("{assembly}")) To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings. diff --git a/src/Microsoft.EntityFrameworkCore.InMemory/Extensions/InMemoryDbContextOptionsExtensions.cs b/src/Microsoft.EntityFrameworkCore.InMemory/Extensions/InMemoryDbContextOptionsExtensions.cs index e916b47236d..13168d7adb5 100644 --- a/src/Microsoft.EntityFrameworkCore.InMemory/Extensions/InMemoryDbContextOptionsExtensions.cs +++ b/src/Microsoft.EntityFrameworkCore.InMemory/Extensions/InMemoryDbContextOptionsExtensions.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure.Internal; @@ -12,13 +13,24 @@ namespace Microsoft.EntityFrameworkCore { public static class InMemoryDbContextOptionsExtensions { - public static InMemoryDbContextOptionsBuilder UseInMemoryDatabase([NotNull] this DbContextOptionsBuilder optionsBuilder) + public static DbContextOptionsBuilder UseInMemoryDatabase( + [NotNull] this DbContextOptionsBuilder optionsBuilder, + [CanBeNull] Action inMemoryOptionsAction = null) { Check.NotNull(optionsBuilder, nameof(optionsBuilder)); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(new InMemoryOptionsExtension()); - return new InMemoryDbContextOptionsBuilder(optionsBuilder); + inMemoryOptionsAction?.Invoke(new InMemoryDbContextOptionsBuilder(optionsBuilder)); + + return optionsBuilder; } + + public static DbContextOptionsBuilder UseInMemoryDatabase( + [NotNull] this DbContextOptionsBuilder optionsBuilder, + [CanBeNull] Action inMemoryOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder)UseInMemoryDatabase( + (DbContextOptionsBuilder)optionsBuilder, inMemoryOptionsAction); } } diff --git a/src/Microsoft.EntityFrameworkCore.SqlServer/Extensions/SqlServerDbContextOptionsExtensions.cs b/src/Microsoft.EntityFrameworkCore.SqlServer/Extensions/SqlServerDbContextOptionsExtensions.cs index 505636bcc4c..d54a2603fd9 100644 --- a/src/Microsoft.EntityFrameworkCore.SqlServer/Extensions/SqlServerDbContextOptionsExtensions.cs +++ b/src/Microsoft.EntityFrameworkCore.SqlServer/Extensions/SqlServerDbContextOptionsExtensions.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using System.Data.Common; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -16,11 +17,14 @@ public static class SqlServerDbContextOptionsExtensions /// /// Configures the context to connect to a Microsoft SQL Server database. /// - /// The options for the context. + /// A builder for setting options on the context. /// The connection string of the database to connect to. - /// An options builder to allow additional SQL Server specific configuration. - public static SqlServerDbContextOptionsBuilder UseSqlServer( - [NotNull] this DbContextOptionsBuilder optionsBuilder, [NotNull] string connectionString) + /// An optional action to allow additional SQL Server specific configuration. + /// The options builder so that further configuration can be chained. + public static DbContextOptionsBuilder UseSqlServer( + [NotNull] this DbContextOptionsBuilder optionsBuilder, + [NotNull] string connectionString, + [CanBeNull] Action sqlServerOptionsAction = null) { Check.NotNull(optionsBuilder, nameof(optionsBuilder)); Check.NotEmpty(connectionString, nameof(connectionString)); @@ -29,22 +33,27 @@ public static SqlServerDbContextOptionsBuilder UseSqlServer( extension.ConnectionString = connectionString; ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); - return new SqlServerDbContextOptionsBuilder(optionsBuilder); + sqlServerOptionsAction?.Invoke(new SqlServerDbContextOptionsBuilder(optionsBuilder)); + + return optionsBuilder; } // Note: Decision made to use DbConnection not SqlConnection: Issue #772 /// /// Configures the context to connect to a Microsoft SQL Server database. /// - /// The options for the context. + /// A builder for setting options on the context. /// /// An existing to be used to connect to the database. If the connection is /// in the open state then EF will not open or close the connection. If the connection is in the closed /// state then EF will open and close the connection as needed. /// - /// An options builder to allow additional SQL Server specific configuration. - public static SqlServerDbContextOptionsBuilder UseSqlServer( - [NotNull] this DbContextOptionsBuilder optionsBuilder, [NotNull] DbConnection connection) + /// An optional action to allow additional SQL Server specific configuration. + /// The options builder so that further configuration can be chained. + public static DbContextOptionsBuilder UseSqlServer( + [NotNull] this DbContextOptionsBuilder optionsBuilder, + [NotNull] DbConnection connection, + [CanBeNull] Action sqlServerOptionsAction = null) { Check.NotNull(optionsBuilder, nameof(optionsBuilder)); Check.NotNull(connection, nameof(connection)); @@ -53,9 +62,46 @@ public static SqlServerDbContextOptionsBuilder UseSqlServer( extension.Connection = connection; ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); - return new SqlServerDbContextOptionsBuilder(optionsBuilder); + sqlServerOptionsAction?.Invoke(new SqlServerDbContextOptionsBuilder(optionsBuilder)); + + return optionsBuilder; } + /// + /// Configures the context to connect to a Microsoft SQL Server database. + /// + /// A builder for setting options on the context. + /// The connection string of the database to connect to. + /// An optional action to allow additional SQL Server specific configuration. + /// The options builder so that further configuration can be chained. + public static DbContextOptionsBuilder UseSqlServer( + [NotNull] this DbContextOptionsBuilder optionsBuilder, + [NotNull] string connectionString, + [CanBeNull] Action sqlServerOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder)UseSqlServer( + (DbContextOptionsBuilder)optionsBuilder, connectionString, sqlServerOptionsAction); + + // Note: Decision made to use DbConnection not SqlConnection: Issue #772 + /// + /// Configures the context to connect to a Microsoft SQL Server database. + /// + /// A builder for setting options on the context. + /// + /// An existing to be used to connect to the database. If the connection is + /// in the open state then EF will not open or close the connection. If the connection is in the closed + /// state then EF will open and close the connection as needed. + /// + /// An optional action to allow additional SQL Server specific configuration. + /// The options builder so that further configuration can be chained. + public static DbContextOptionsBuilder UseSqlServer( + [NotNull] this DbContextOptionsBuilder optionsBuilder, + [NotNull] DbConnection connection, + [CanBeNull] Action sqlServerOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder)UseSqlServer( + (DbContextOptionsBuilder)optionsBuilder, connection, sqlServerOptionsAction); + private static SqlServerOptionsExtension GetOrCreateExtension(DbContextOptionsBuilder optionsBuilder) { var existing = optionsBuilder.Options.FindExtension(); diff --git a/src/Microsoft.EntityFrameworkCore.SqlServer/Storage/Internal/SqlServerConnection.cs b/src/Microsoft.EntityFrameworkCore.SqlServer/Storage/Internal/SqlServerConnection.cs index 1deff3a6e06..df3ca1bc3d4 100644 --- a/src/Microsoft.EntityFrameworkCore.SqlServer/Storage/Internal/SqlServerConnection.cs +++ b/src/Microsoft.EntityFrameworkCore.SqlServer/Storage/Internal/SqlServerConnection.cs @@ -32,16 +32,12 @@ private SqlServerConnection( protected override DbConnection CreateDbConnection() => new SqlConnection(ConnectionString); + // TODO use clone connection method once implemented see #1406 public virtual ISqlServerConnection CreateMasterConnection() - { - var builder = new SqlConnectionStringBuilder { ConnectionString = ConnectionString, InitialCatalog = "master" }; - - // TODO use clone connection method once implemented see #1406 - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(builder.ConnectionString).CommandTimeout(CommandTimeout ?? DefaultMasterConnectionCommandTimeout); - - return new SqlServerConnection(optionsBuilder.Options, Logger); - } + => new SqlServerConnection(new DbContextOptionsBuilder() + .UseSqlServer( + new SqlConnectionStringBuilder { ConnectionString = ConnectionString, InitialCatalog = "master" }.ConnectionString, + b => b.CommandTimeout(CommandTimeout ?? DefaultMasterConnectionCommandTimeout)).Options, Logger); public override bool IsMultipleActiveResultSetsEnabled => (bool)(_multipleActiveResultSetsEnabled diff --git a/src/Microsoft.EntityFrameworkCore.Sqlite/SqliteDbContextOptionsBuilderExtensions.cs b/src/Microsoft.EntityFrameworkCore.Sqlite/SqliteDbContextOptionsBuilderExtensions.cs index 6141ddbceff..b1815e6e0d4 100644 --- a/src/Microsoft.EntityFrameworkCore.Sqlite/SqliteDbContextOptionsBuilderExtensions.cs +++ b/src/Microsoft.EntityFrameworkCore.Sqlite/SqliteDbContextOptionsBuilderExtensions.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using System.Data.Common; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -11,30 +12,56 @@ namespace Microsoft.EntityFrameworkCore { public static class SqliteDbContextOptionsBuilderExtensions { - public static SqliteDbContextOptionsBuilder UseSqlite([NotNull] this DbContextOptionsBuilder options, [NotNull] string connectionString) + public static DbContextOptionsBuilder UseSqlite( + [NotNull] this DbContextOptionsBuilder optionsBuilder, + [NotNull] string connectionString, + [CanBeNull] Action sqliteOptionsAction = null) { - Check.NotNull(options, nameof(options)); + Check.NotNull(optionsBuilder, nameof(optionsBuilder)); Check.NotEmpty(connectionString, nameof(connectionString)); - var extension = GetOrCreateExtension(options); + var extension = GetOrCreateExtension(optionsBuilder); extension.ConnectionString = connectionString; - ((IDbContextOptionsBuilderInfrastructure)options).AddOrUpdateExtension(extension); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); - return new SqliteDbContextOptionsBuilder(options); + sqliteOptionsAction?.Invoke(new SqliteDbContextOptionsBuilder(optionsBuilder)); + + return optionsBuilder; } - public static SqliteDbContextOptionsBuilder UseSqlite([NotNull] this DbContextOptionsBuilder options, [NotNull] DbConnection connection) + public static DbContextOptionsBuilder UseSqlite( + [NotNull] this DbContextOptionsBuilder optionsBuilder, + [NotNull] DbConnection connection, + [CanBeNull] Action sqliteOptionsAction = null) { - Check.NotNull(options, nameof(options)); + Check.NotNull(optionsBuilder, nameof(optionsBuilder)); Check.NotNull(connection, nameof(connection)); - var extension = GetOrCreateExtension(options); + var extension = GetOrCreateExtension(optionsBuilder); extension.Connection = connection; - ((IDbContextOptionsBuilderInfrastructure)options).AddOrUpdateExtension(extension); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); + + sqliteOptionsAction?.Invoke(new SqliteDbContextOptionsBuilder(optionsBuilder)); - return new SqliteDbContextOptionsBuilder(options); + return optionsBuilder; } + public static DbContextOptionsBuilder UseSqlite( + [NotNull] this DbContextOptionsBuilder optionsBuilder, + [NotNull] string connectionString, + [CanBeNull] Action sqliteOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder)UseSqlite( + (DbContextOptionsBuilder)optionsBuilder, connectionString, sqliteOptionsAction); + + public static DbContextOptionsBuilder UseSqlite( + [NotNull] this DbContextOptionsBuilder optionsBuilder, + [NotNull] DbConnection connection, + [CanBeNull] Action sqliteOptionsAction = null) + where TContext : DbContext + => (DbContextOptionsBuilder)UseSqlite( + (DbContextOptionsBuilder)optionsBuilder, connection, sqliteOptionsAction); + private static SqliteOptionsExtension GetOrCreateExtension(DbContextOptionsBuilder options) { var existingExtension = options.Options.FindExtension(); diff --git a/src/Microsoft.EntityFrameworkCore/DbContext.cs b/src/Microsoft.EntityFrameworkCore/DbContext.cs index 1e05660b895..478ae283731 100644 --- a/src/Microsoft.EntityFrameworkCore/DbContext.cs +++ b/src/Microsoft.EntityFrameworkCore/DbContext.cs @@ -46,12 +46,7 @@ namespace Microsoft.EntityFrameworkCore /// public class DbContext : IDisposable, IInfrastructure { - private static readonly ConcurrentDictionary _optionsTypes = new ConcurrentDictionary(); - - private readonly IServiceProvider _internalServicesProvider; private readonly DbContextOptions _options; - private readonly ILoggerFactory _loggerFactory; - private readonly IMemoryCache _memoryCache; private IDbContextServices _contextServices; private IDbSetInitializer _setInitializer; @@ -72,63 +67,9 @@ public class DbContext : IDisposable, IInfrastructure /// /// method will be called to configure the database (and other options) to be used for this context. /// - /// - /// EF will create and manage an internal service provider for all internal EF services. - /// /// - /// - /// Optional that will be used to create instances - /// for logging done by this context. - /// - /// - /// Optional to be used for query caching by this context. The context will - /// create and manage a memory cache if none is passed in. - /// - protected DbContext( - [CanBeNull] ILoggerFactory loggerFactory = null, - [CanBeNull] IMemoryCache memoryCache = null) - : this(new DbContextOptions(), loggerFactory, memoryCache) - { - } - - /// - /// - /// Initializes a new instance of the class. The - /// - /// method will be called to configure the database (and other options) to be used for this context. - /// - /// - /// The service provider used for all EF internal services is passed into this constructor. This is only - /// needed if the application needs to manage the service provider in a special way, or if the application - /// needs to modify some of the internal services used by EF. External services used by EF, such as the - /// and , should be passed as arguments to this - /// constructor rather than being configured in this internal service provider. - /// - /// - /// The internal service provider must contain all the services required by Entity Framework (and - /// the database being used). The Entity Framework services can be registered using the - /// method. - /// Most databases also provide an extension method on to register the - /// services required. For example, the Microsoft SQL Server provider includes an AddSqlServer() method - /// to add the required services. - /// - /// - /// - /// The service provider to be used for all internal services needed by the Entity Framework. - /// - /// - /// Optional that will be used to create instances - /// for logging done by this context. - /// - /// - /// Optional to be used for query caching by this context. The context will - /// create and manage a memory cache if none is passed in. - /// - protected DbContext( - [NotNull] IServiceProvider internalServicesProvider, - [CanBeNull] ILoggerFactory loggerFactory = null, - [CanBeNull] IMemoryCache memoryCache = null) - : this(internalServicesProvider, new DbContextOptions(), loggerFactory, memoryCache) + protected DbContext() + : this(new DbContextOptions()) { } @@ -138,93 +79,26 @@ protected DbContext( /// The method will still be called to allow further /// configuration of the options. /// - /// - /// EF will create and manage an internal service provider for all internal EF services. - /// /// /// The options for this context. - /// - /// Optional that will be used to create instances - /// for logging done by this context. - /// - /// - /// Optional to be used for query caching by this context. The context will - /// create and manage a memory cache if none is passed in. - /// - public DbContext( - [NotNull] DbContextOptions options, - [CanBeNull] ILoggerFactory loggerFactory = null, - [CanBeNull] IMemoryCache memoryCache = null) + public DbContext([NotNull] DbContextOptions options) { Check.NotNull(options, nameof(options)); _options = options; - _loggerFactory = loggerFactory; - _memoryCache = memoryCache; InitializeSets(ServiceProviderCache.Instance.GetOrAdd(options)); } - /// - /// - /// Initializes a new instance of the class using the specified options. - /// The method will still be called to allow further - /// configuration of the options. - /// - /// - /// The service provider used for all EF internal services is passed into this constructor. This is only - /// needed if the application needs to manage the service provider in a special way, or if the application - /// needs to modify some of the internal services used by EF. External services used by EF, such as the - /// and , should be passed as arguments to this - /// constructor rather than being configured in this internal service provider. - /// - /// - /// The internal service provider must contain all the services required by Entity Framework (and - /// the database being used). The Entity Framework services can be registered using the - /// method. - /// Most databases also provide an extension method on to register the - /// services required. For example, the Microsoft SQL Server provider includes an AddSqlServer() method - /// to add the required services. - /// - /// - /// - /// The service provider to be used for all internal services needed by the Entity Framework. - /// - /// The options for this context. - /// - /// Optional that will be used to create instances - /// for logging done by this context. - /// - /// - /// Optional to be used for query caching by this context. The context will - /// create and manage a memory cache if none is passed in. - /// - public DbContext( - [NotNull] IServiceProvider internalServicesProvider, - [NotNull] DbContextOptions options, - [CanBeNull] ILoggerFactory loggerFactory = null, - [CanBeNull] IMemoryCache memoryCache = null) - { - Check.NotNull(internalServicesProvider, nameof(internalServicesProvider)); - Check.NotNull(options, nameof(options)); - - _internalServicesProvider = internalServicesProvider; - _options = options; - _loggerFactory = loggerFactory; - _memoryCache = memoryCache; - - InitializeSets(internalServicesProvider); - } - private IChangeDetector ChangeDetector => _changeDetector - ?? (_changeDetector = ServiceProvider.GetRequiredService()); + ?? (_changeDetector = InternalServiceProvider.GetRequiredService()); private IStateManager StateManager => _stateManager - ?? (_stateManager = ServiceProvider.GetRequiredService()); + ?? (_stateManager = InternalServiceProvider.GetRequiredService()); - private IServiceProvider ServiceProvider + private IServiceProvider InternalServiceProvider { get { @@ -232,7 +106,7 @@ private IServiceProvider ServiceProvider { throw new ObjectDisposedException(GetType().Name); } - return (_contextServices ?? (_contextServices = InitializeServices())).ServiceProvider; + return (_contextServices ?? (_contextServices = InitializeServices())).InternalServiceProvider; } } @@ -251,9 +125,10 @@ private IDbContextServices InitializeServices() OnConfiguring(optionsBuilder); - var providerSource = _internalServicesProvider != null ? ServiceProviderSource.Explicit : ServiceProviderSource.Implicit; - - var serviceProvider = _internalServicesProvider ?? ServiceProviderCache.Instance.GetOrAdd(optionsBuilder.Options); + var options = optionsBuilder.Options; + + var serviceProvider = options.FindExtension()?.InternalServiceProvider + ?? ServiceProviderCache.Instance.GetOrAdd(options); _serviceScope = serviceProvider .GetRequiredService() @@ -263,7 +138,7 @@ private IDbContextServices InitializeServices() var contextServices = scopedServiceProvider .GetRequiredService() - .Initialize(scopedServiceProvider, optionsBuilder.Options, _loggerFactory, _memoryCache, this, providerSource); + .Initialize(scopedServiceProvider, options, this); _logger = scopedServiceProvider.GetRequiredService>(); @@ -287,7 +162,7 @@ private void InitializeSets(IServiceProvider internalServicesProvider) /// not directly exposed in the public API surface. /// /// - IServiceProvider IInfrastructure.Instance => ServiceProvider; + IServiceProvider IInfrastructure.Instance => InternalServiceProvider; /// /// @@ -516,7 +391,7 @@ private void SetEntityState(InternalEntityEntry entry, EntityState entityState) if (entry.EntityState == EntityState.Detached) { (_graphAttacher - ?? (_graphAttacher = ServiceProvider.GetRequiredService())) + ?? (_graphAttacher = InternalServiceProvider.GetRequiredService())) .AttachGraph(entry, entityState); } else @@ -877,14 +752,14 @@ public virtual void RemoveRange([NotNull] IEnumerable entities) /// public virtual ChangeTracker ChangeTracker => _changeTracker - ?? (_changeTracker = ServiceProvider.GetRequiredService().Create()); + ?? (_changeTracker = InternalServiceProvider.GetRequiredService().Create()); /// /// The metadata about the shape of entities, the relationships between them, and how they map to the database. /// public virtual IModel Model => _model - ?? (_model = ServiceProvider.GetRequiredService()); + ?? (_model = InternalServiceProvider.GetRequiredService()); /// /// Creates a that can be used to query and save instances of . @@ -899,7 +774,7 @@ public virtual DbSet Set() where TEntity : class } return (_setInitializer - ?? (_setInitializer = ServiceProvider.GetRequiredService())).CreateSet(this); + ?? (_setInitializer = InternalServiceProvider.GetRequiredService())).CreateSet(this); } } } diff --git a/src/Microsoft.EntityFrameworkCore/DbContextOptionsBuilder.cs b/src/Microsoft.EntityFrameworkCore/DbContextOptionsBuilder.cs index 765e4a97d5e..6303da53291 100644 --- a/src/Microsoft.EntityFrameworkCore/DbContextOptionsBuilder.cs +++ b/src/Microsoft.EntityFrameworkCore/DbContextOptionsBuilder.cs @@ -8,6 +8,8 @@ using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Utilities; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging; namespace Microsoft.EntityFrameworkCore { @@ -71,14 +73,17 @@ public DbContextOptionsBuilder([NotNull] DbContextOptions options) /// /// The model to be used. /// The same builder instance so that multiple calls can be chained. - public virtual DbContextOptionsBuilder UseModel([NotNull] IModel model) - { - Check.NotNull(model, nameof(model)); + public virtual DbContextOptionsBuilder UseModel([NotNull] IModel model) + => SetOption(e => e.Model = Check.NotNull(model, nameof(model))); - SetOption(e => e.Model = model); + public virtual DbContextOptionsBuilder UseLoggerFactory([CanBeNull] ILoggerFactory loggerFactory) + => SetOption(e => e.LoggerFactory = loggerFactory); - return this; - } + public virtual DbContextOptionsBuilder UseMemoryCache([CanBeNull] IMemoryCache memoryCache) + => SetOption(e => e.MemoryCache = memoryCache); + + public virtual DbContextOptionsBuilder UseInternalServiceProvider([CanBeNull] IServiceProvider serviceProvider) + => SetOption(e => e.InternalServiceProvider = serviceProvider); /// /// Enables application data to be included in exception messages, logging, etc. This can include the values assigned to properties @@ -107,10 +112,8 @@ void IDbContextOptionsBuilderInfrastructure.AddOrUpdateExtension(TEx _options = _options.WithExtension(extension); } - private DbContextOptionsBuilder SetOption([NotNull] Action setAction) + private DbContextOptionsBuilder SetOption(Action setAction) { - Check.NotNull(setAction, nameof(setAction)); - var existingExtension = Options.FindExtension(); var extension diff --git a/src/Microsoft.EntityFrameworkCore/DbContextOptionsBuilder`.cs b/src/Microsoft.EntityFrameworkCore/DbContextOptionsBuilder`.cs index 0399dc4caba..6a349781218 100644 --- a/src/Microsoft.EntityFrameworkCore/DbContextOptionsBuilder`.cs +++ b/src/Microsoft.EntityFrameworkCore/DbContextOptionsBuilder`.cs @@ -1,9 +1,12 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging; namespace Microsoft.EntityFrameworkCore { @@ -54,5 +57,24 @@ public DbContextOptionsBuilder([NotNull] DbContextOptions options) /// The same builder instance so that multiple calls can be chained. public new virtual DbContextOptionsBuilder UseModel([NotNull] IModel model) => (DbContextOptionsBuilder)base.UseModel(model); + + public new virtual DbContextOptionsBuilder UseLoggerFactory([CanBeNull] ILoggerFactory loggerFactory) + => (DbContextOptionsBuilder)base.UseLoggerFactory(loggerFactory); + + public new virtual DbContextOptionsBuilder UseMemoryCache([CanBeNull] IMemoryCache memoryCache) + => (DbContextOptionsBuilder)base.UseMemoryCache(memoryCache); + + public new virtual DbContextOptionsBuilder UseInternalServiceProvider([CanBeNull] IServiceProvider serviceProvider) + => (DbContextOptionsBuilder)base.UseInternalServiceProvider(serviceProvider); + + /// + /// Enables application data to be included in exception messages, logging, etc. This can include the values assigned to properties + /// of your entity instances, parameter values for commands being sent to the database, and other such data. You should only enable + /// this flag if you have the appropriate security measures in place based on the sensitivity of this data. + /// + /// The same builder instance so that multiple calls can be chained. + public new virtual DbContextOptionsBuilder EnableSensitiveDataLogging() + => (DbContextOptionsBuilder)base.EnableSensitiveDataLogging(); + } } diff --git a/src/Microsoft.EntityFrameworkCore/EntityFrameworkServiceCollectionExtensions.cs b/src/Microsoft.EntityFrameworkCore/EntityFrameworkServiceCollectionExtensions.cs index b541f8edf26..b4edb28bdfc 100644 --- a/src/Microsoft.EntityFrameworkCore/EntityFrameworkServiceCollectionExtensions.cs +++ b/src/Microsoft.EntityFrameworkCore/EntityFrameworkServiceCollectionExtensions.cs @@ -17,6 +17,7 @@ using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Utilities; using Microsoft.EntityFrameworkCore.ValueGeneration; +using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Remotion.Linq.Parsing.Structure.NodeTypeProviders; @@ -79,32 +80,39 @@ public static IServiceCollection AddDbContext( [NotNull] this IServiceCollection serviceCollection, [CanBeNull] Action optionsAction = null) where TContext : DbContext + => AddDbContext(serviceCollection, (p, b) => optionsAction?.Invoke(b)); + + public static IServiceCollection AddDbContext( + [NotNull] this IServiceCollection serviceCollection, + [CanBeNull] Action optionsAction) + where TContext : DbContext { serviceCollection.AddCaching(); serviceCollection.AddLogging(); - serviceCollection.AddSingleton(_ => DbContextOptionsFactory(optionsAction)); - serviceCollection.AddSingleton(p => p.GetRequiredService>()); + serviceCollection.TryAddSingleton(p => DbContextOptionsFactory(p, optionsAction)); + serviceCollection.TryAddSingleton(p => p.GetRequiredService>()); - serviceCollection.AddScoped(); + serviceCollection.TryAddScoped(); return serviceCollection; } private static DbContextOptions DbContextOptionsFactory( - [CanBeNull] Action optionsAction) + [NotNull] IServiceProvider applicationServiceProvider, + [CanBeNull] Action optionsAction) where TContext : DbContext { var options = new DbContextOptions(new Dictionary()); - if (optionsAction != null) - { - var builder = new DbContextOptionsBuilder(options); - optionsAction(builder); - options = builder.Options; - } + var builder = new DbContextOptionsBuilder(options); + + builder.UseMemoryCache(applicationServiceProvider.GetService()); + builder.UseLoggerFactory(applicationServiceProvider.GetService()); + + optionsAction?.Invoke(applicationServiceProvider, builder); - return options; + return builder.Options; } /// @@ -127,8 +135,8 @@ private static DbContextOptions DbContextOptionsFactory( /// /// For derived contexts to be registered in the and resolve their services /// from the you must chain a call to the - /// method on the returned - /// . + /// + /// method on the returned . /// /// /// diff --git a/src/Microsoft.EntityFrameworkCore/Internal/CoreOptionsExtension.cs b/src/Microsoft.EntityFrameworkCore/Internal/CoreOptionsExtension.cs index fa51281f6b8..d64e98d45a9 100644 --- a/src/Microsoft.EntityFrameworkCore/Internal/CoreOptionsExtension.cs +++ b/src/Microsoft.EntityFrameworkCore/Internal/CoreOptionsExtension.cs @@ -5,7 +5,9 @@ using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; namespace Microsoft.EntityFrameworkCore.Internal { @@ -14,7 +16,10 @@ namespace Microsoft.EntityFrameworkCore.Internal /// public class CoreOptionsExtension : IDbContextOptionsExtension { + private IServiceProvider _internalServiceProvider; private IModel _model; + private ILoggerFactory _loggerFactory; + private IMemoryCache _memoryCache; private bool _isSensitiveDataLoggingEnabled; /// @@ -37,8 +42,11 @@ public CoreOptionsExtension() /// The to copy options from. public CoreOptionsExtension([NotNull] CoreOptionsExtension copyFrom) { - _isSensitiveDataLoggingEnabled = copyFrom.IsSensitiveDataLoggingEnabled; + _internalServiceProvider = copyFrom.InternalServiceProvider; _model = copyFrom.Model; + _loggerFactory = copyFrom.LoggerFactory; + _memoryCache = copyFrom.MemoryCache; + _isSensitiveDataLoggingEnabled = copyFrom.IsSensitiveDataLoggingEnabled; } /// @@ -69,6 +77,24 @@ public virtual IModel Model [param: CanBeNull] set { _model = value; } } + public virtual ILoggerFactory LoggerFactory + { + get { return _loggerFactory; } + [param: CanBeNull] set { _loggerFactory = value; } + } + + public virtual IMemoryCache MemoryCache + { + get { return _memoryCache; } + [param: CanBeNull] set { _memoryCache = value; } + } + + public virtual IServiceProvider InternalServiceProvider + { + get { return _internalServiceProvider; } + [param: CanBeNull] set { _internalServiceProvider = value; } + } + /// /// Adds the services required to make the selected options work. This is used when there is no external /// and EF is maintaining its own service provider internally. Since all the core services are already added to the service provider, diff --git a/src/Microsoft.EntityFrameworkCore/Internal/DatabaseProviderSelector.cs b/src/Microsoft.EntityFrameworkCore/Internal/DatabaseProviderSelector.cs index 1b1dc0e3fb0..b56194fc269 100644 --- a/src/Microsoft.EntityFrameworkCore/Internal/DatabaseProviderSelector.cs +++ b/src/Microsoft.EntityFrameworkCore/Internal/DatabaseProviderSelector.cs @@ -26,7 +26,7 @@ public DatabaseProviderSelector( _providers = providers?.ToArray() ?? new IDatabaseProvider[0]; } - public virtual IDatabaseProviderServices SelectServices(ServiceProviderSource providerSource) + public virtual IDatabaseProviderServices SelectServices() { var configured = _providers.Where(f => f.IsConfigured(_contextOptions)).ToArray(); @@ -42,11 +42,7 @@ public virtual IDatabaseProviderServices SelectServices(ServiceProviderSource pr if (_providers.Length == 0) { - if (providerSource == ServiceProviderSource.Implicit) - { - throw new InvalidOperationException(CoreStrings.NoProviderConfigured); - } - throw new InvalidOperationException(CoreStrings.NoProviderServices); + throw new InvalidOperationException(CoreStrings.NoProviderConfigured); } if (_providers.Length > 1) diff --git a/src/Microsoft.EntityFrameworkCore/Internal/DbContextServices.cs b/src/Microsoft.EntityFrameworkCore/Internal/DbContextServices.cs index e44be553725..db01eb921a8 100644 --- a/src/Microsoft.EntityFrameworkCore/Internal/DbContextServices.cs +++ b/src/Microsoft.EntityFrameworkCore/Internal/DbContextServices.cs @@ -17,8 +17,6 @@ public class DbContextServices : IDbContextServices { private IServiceProvider _provider; private IDbContextOptions _contextOptions; - private ILoggerFactory _loggerFactory; - private IMemoryCache _memoryCache; private DbContext _context; private LazyRef _modelFromSource; private LazyRef _providerServices; @@ -27,10 +25,7 @@ public class DbContextServices : IDbContextServices public virtual IDbContextServices Initialize( IServiceProvider scopedProvider, IDbContextOptions contextOptions, - ILoggerFactory loggerFactory, - IMemoryCache memoryCache, - DbContext context, - ServiceProviderSource serviceProviderSource) + DbContext context) { Check.NotNull(scopedProvider, nameof(scopedProvider)); Check.NotNull(contextOptions, nameof(contextOptions)); @@ -38,12 +33,10 @@ public virtual IDbContextServices Initialize( _provider = scopedProvider; _contextOptions = contextOptions; - _loggerFactory = loggerFactory; - _memoryCache = memoryCache; _context = context; _providerServices = new LazyRef(() => - _provider.GetRequiredService().SelectServices(serviceProviderSource)); + _provider.GetRequiredService().SelectServices()); _modelFromSource = new LazyRef(CreateModel); @@ -74,11 +67,13 @@ private IModel CreateModel() public virtual DbContext Context => _context; - public virtual IModel Model => _contextOptions.FindExtension()?.Model ?? _modelFromSource.Value; + public virtual IModel Model => CoreOptions?.Model ?? _modelFromSource.Value; - public virtual ILoggerFactory LoggerFactory => _loggerFactory ?? _provider.GetRequiredService(); + public virtual ILoggerFactory LoggerFactory => CoreOptions?.LoggerFactory ?? _provider.GetRequiredService(); - public virtual IMemoryCache MemoryCache => _memoryCache ?? _provider.GetRequiredService(); + public virtual IMemoryCache MemoryCache => CoreOptions?.MemoryCache ?? _provider.GetRequiredService(); + + private CoreOptionsExtension CoreOptions => _contextOptions.FindExtension(); public virtual IDbContextOptions ContextOptions => _contextOptions; @@ -94,6 +89,6 @@ public virtual IDatabaseProviderServices DatabaseProviderServices } } - public virtual IServiceProvider ServiceProvider => _provider; + public virtual IServiceProvider InternalServiceProvider => _provider; } } diff --git a/src/Microsoft.EntityFrameworkCore/Internal/IDatabaseProviderSelector.cs b/src/Microsoft.EntityFrameworkCore/Internal/IDatabaseProviderSelector.cs index 11dcef29b1e..82208381a22 100644 --- a/src/Microsoft.EntityFrameworkCore/Internal/IDatabaseProviderSelector.cs +++ b/src/Microsoft.EntityFrameworkCore/Internal/IDatabaseProviderSelector.cs @@ -7,6 +7,6 @@ namespace Microsoft.EntityFrameworkCore.Internal { public interface IDatabaseProviderSelector { - IDatabaseProviderServices SelectServices(ServiceProviderSource providerSource); + IDatabaseProviderServices SelectServices(); } } diff --git a/src/Microsoft.EntityFrameworkCore/Internal/IDbContextServices.cs b/src/Microsoft.EntityFrameworkCore/Internal/IDbContextServices.cs index ea345b630ba..d5e1e6d5753 100644 --- a/src/Microsoft.EntityFrameworkCore/Internal/IDbContextServices.cs +++ b/src/Microsoft.EntityFrameworkCore/Internal/IDbContextServices.cs @@ -16,10 +16,7 @@ public interface IDbContextServices IDbContextServices Initialize( [NotNull] IServiceProvider scopedProvider, [NotNull] IDbContextOptions contextOptions, - [CanBeNull] ILoggerFactory loggerFactory, - [CanBeNull] IMemoryCache memoryCache, - [NotNull] DbContext context, - ServiceProviderSource serviceProviderSource); + [NotNull] DbContext context); DbContext Context { get; } IModel Model { get; } @@ -27,6 +24,6 @@ IDbContextServices Initialize( IMemoryCache MemoryCache { get; } IDbContextOptions ContextOptions { get; } IDatabaseProviderServices DatabaseProviderServices { get; } - IServiceProvider ServiceProvider { get; } + IServiceProvider InternalServiceProvider { get; } } } diff --git a/src/Microsoft.EntityFrameworkCore/Internal/ServiceProviderSource.cs b/src/Microsoft.EntityFrameworkCore/Internal/ServiceProviderSource.cs deleted file mode 100644 index 34ae153599b..00000000000 --- a/src/Microsoft.EntityFrameworkCore/Internal/ServiceProviderSource.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.EntityFrameworkCore.Internal -{ - public enum ServiceProviderSource - { - Explicit, - Implicit - } -} diff --git a/src/Microsoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.csproj b/src/Microsoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.csproj index 3ac8d82d86d..dccbe0ecbe4 100644 --- a/src/Microsoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.csproj +++ b/src/Microsoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.csproj @@ -209,7 +209,6 @@ - diff --git a/test/Microsoft.EntityFrameworkCore.Commands.FunctionalTests/Design/OperationExecutorTest.cs b/test/Microsoft.EntityFrameworkCore.Commands.FunctionalTests/Design/OperationExecutorTest.cs index ddac36c445a..7ede7993c6a 100644 --- a/test/Microsoft.EntityFrameworkCore.Commands.FunctionalTests/Design/OperationExecutorTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Commands.FunctionalTests/Design/OperationExecutorTest.cs @@ -433,8 +433,9 @@ internal class MyContext : DbContext protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder - .UseSqlServer(""Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MyProject.MyContext;Integrated Security=True"") - .MigrationsAssembly(""UnknownAssembly""); + .UseSqlServer( + ""Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MyProject.MyContext;Integrated Security=True"", + b => b.MigrationsAssembly(""UnknownAssembly"")); } } diff --git a/test/Microsoft.EntityFrameworkCore.CrossStore.FunctionalTests/SharedCrossStoreFixture.cs b/test/Microsoft.EntityFrameworkCore.CrossStore.FunctionalTests/SharedCrossStoreFixture.cs index d035aabcfab..9530a88228e 100644 --- a/test/Microsoft.EntityFrameworkCore.CrossStore.FunctionalTests/SharedCrossStoreFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.CrossStore.FunctionalTests/SharedCrossStoreFixture.cs @@ -57,10 +57,11 @@ public override CrossStoreContext CreateContext(TestStore testStore) var inMemoryTestStore = testStore as InMemoryTestStore; if (inMemoryTestStore != null) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); - return new CrossStoreContext(_serviceProvider, optionsBuilder.Options); + return new CrossStoreContext(optionsBuilder.Options); } var sqliteTestStore = testStore as SqliteTestStore; @@ -69,7 +70,7 @@ public override CrossStoreContext CreateContext(TestStore testStore) var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseSqlite(sqliteTestStore.Connection); - var context = new CrossStoreContext(_serviceProvider, optionsBuilder.Options); + var context = new CrossStoreContext(optionsBuilder.Options); context.Database.EnsureCreated(); context.Database.UseTransaction(sqliteTestStore.Transaction); @@ -82,7 +83,7 @@ public override CrossStoreContext CreateContext(TestStore testStore) var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseSqlServer(sqlServerTestStore.Connection); - var context = new CrossStoreContext(_serviceProvider, optionsBuilder.Options); + var context = new CrossStoreContext(optionsBuilder.Options); context.Database.EnsureCreated(); context.Database.UseTransaction(sqlServerTestStore.Transaction); diff --git a/test/Microsoft.EntityFrameworkCore.CrossStore.FunctionalTests/TestModels/CrossStoreContext.cs b/test/Microsoft.EntityFrameworkCore.CrossStore.FunctionalTests/TestModels/CrossStoreContext.cs index 8e0adee216e..11c6e1d345e 100644 --- a/test/Microsoft.EntityFrameworkCore.CrossStore.FunctionalTests/TestModels/CrossStoreContext.cs +++ b/test/Microsoft.EntityFrameworkCore.CrossStore.FunctionalTests/TestModels/CrossStoreContext.cs @@ -8,8 +8,8 @@ namespace Microsoft.EntityFrameworkCore.CrossStore.FunctionalTests.TestModels { public class CrossStoreContext : DbContext { - public CrossStoreContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public CrossStoreContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/DataAnnotationFixtureBase.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/DataAnnotationFixtureBase.cs index cf3e6b41159..c3dd2b6d31c 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/DataAnnotationFixtureBase.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/DataAnnotationFixtureBase.cs @@ -22,8 +22,8 @@ protected virtual void OnModelCreating(ModelBuilder modelBuilder) public class DataAnnotationContext : DbContext { - public DataAnnotationContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public DataAnnotationContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/DatabaseErrorLogStateTest.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/DatabaseErrorLogStateTest.cs index e081f5c6495..ec65187160c 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/DatabaseErrorLogStateTest.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/DatabaseErrorLogStateTest.cs @@ -191,9 +191,11 @@ public async Task SaveChanges_logs_concurrent_access(bool async) public class BloggingContext : DbContext { - public BloggingContext(IServiceProvider provider) - : base(provider) + private readonly IServiceProvider _serviceProvider; + + public BloggingContext(IServiceProvider serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Blogs { get; set; } @@ -217,13 +219,13 @@ public Blog(bool jimSaysThrow) public string Name { get; set; } } - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity().HasKey(b => b.Url); - } + protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity().HasKey(b => b.Url); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseInMemoryDatabase(); + => optionsBuilder + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); } private class TestLoggerFactory : ILoggerFactory diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/GraphUpdatesTestBase.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/GraphUpdatesTestBase.cs index 7d2aa2b2858..cce1e686dd2 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/GraphUpdatesTestBase.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/GraphUpdatesTestBase.cs @@ -3894,8 +3894,8 @@ protected class OptionalSingleAk2 protected class GraphUpdatesContext : DbContext { - public GraphUpdatesContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public GraphUpdatesContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/ModelSourceTest.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/ModelSourceTest.cs index ca013ea7194..5f12aed81fc 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/ModelSourceTest.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/ModelSourceTest.cs @@ -81,9 +81,11 @@ protected override IModel CreateModel(DbContext context, IConventionSetBuilder c private class JustSomeContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public JustSomeContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Peaks { get; set; } @@ -92,7 +94,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().HasAnnotation("AllYourBaseAreBelongTo", "Us!"); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseInMemoryDatabase(); + => optionsBuilder + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); } private class Base diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/MonsterFixupTestBase.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/MonsterFixupTestBase.cs index 2a54509a69f..520bfd147eb 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/MonsterFixupTestBase.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/MonsterFixupTestBase.cs @@ -1601,15 +1601,15 @@ protected void NavigationVerification(Func createContext) protected abstract void CreateAndSeedDatabase(string databaseName, Func createContext); private SnapshotMonsterContext CreateSnapshotMonsterContext(IServiceProvider serviceProvider, string databaseName = SnapshotDatabaseName) - => new SnapshotMonsterContext(serviceProvider, CreateOptions(databaseName), + => new SnapshotMonsterContext(new DbContextOptionsBuilder(CreateOptions(databaseName)).UseInternalServiceProvider(serviceProvider).Options, OnModelCreating); private ChangedChangingMonsterContext CreateChangedChangingMonsterContext(IServiceProvider serviceProvider, string databaseName = FullNotifyDatabaseName) - => new ChangedChangingMonsterContext(serviceProvider, CreateOptions(databaseName), + => new ChangedChangingMonsterContext(new DbContextOptionsBuilder(CreateOptions(databaseName)).UseInternalServiceProvider(serviceProvider).Options, OnModelCreating); private ChangedOnlyMonsterContext CreateChangedOnlyMonsterContext(IServiceProvider serviceProvider, string databaseName = ChangedOnlyDatabaseName) - => new ChangedOnlyMonsterContext(serviceProvider, CreateOptions(databaseName), + => new ChangedOnlyMonsterContext(new DbContextOptionsBuilder(CreateOptions(databaseName)).UseInternalServiceProvider(serviceProvider).Options, OnModelCreating); public virtual void OnModelCreating(ModelBuilder builder) diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/StoreGeneratedTestBase.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/StoreGeneratedTestBase.cs index 151e4ba9a0e..e3b08207aaa 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/StoreGeneratedTestBase.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/StoreGeneratedTestBase.cs @@ -752,23 +752,19 @@ protected class Gumball protected class StoreGeneratedContext : DbContext { - public StoreGeneratedContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public StoreGeneratedContext(DbContextOptions options) + : base(options) { } public DbSet Gumballs { get; set; } } - protected StoreGeneratedContext CreateContext() - { - return (StoreGeneratedContext)Fixture.CreateContext(TestStore); - } + protected StoreGeneratedContext CreateContext() + => (StoreGeneratedContext)Fixture.CreateContext(TestStore); - public void Dispose() - { - TestStore.Dispose(); - } + public void Dispose() + => TestStore.Dispose(); protected TFixture Fixture { get; } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestHelpers.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestHelpers.cs index 41cf2655a4a..38fa51bd967 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestHelpers.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestHelpers.cs @@ -23,17 +23,21 @@ protected TestHelpers() public static TestHelpers Instance { get; } = new TestHelpers(); - public DbContextOptions CreateOptions(IModel model) + public DbContextOptions CreateOptions(IModel model, IServiceProvider serviceProvider = null) { - var optionsBuilder = new DbContextOptionsBuilder(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInternalServiceProvider(serviceProvider); + UseProviderOptions(optionsBuilder.UseModel(model)); return optionsBuilder.Options; } - public DbContextOptions CreateOptions() + public DbContextOptions CreateOptions(IServiceProvider serviceProvider = null) { - var optionsBuilder = new DbContextOptionsBuilder(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInternalServiceProvider(serviceProvider); + UseProviderOptions(optionsBuilder); return optionsBuilder.Options; @@ -65,27 +69,31 @@ private IServiceProvider CreateServiceProvider( protected virtual void UseProviderOptions(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseInMemoryDatabase(); public DbContext CreateContext(IServiceProvider serviceProvider, IModel model) - => new DbContext(serviceProvider, CreateOptions(model)); + => new DbContext(CreateOptions(model, serviceProvider)); public DbContext CreateContext(IServiceProvider serviceProvider, DbContextOptions options) - => new DbContext(serviceProvider, options); + => new DbContext(new DbContextOptionsBuilder(options).UseInternalServiceProvider(serviceProvider).Options); - public DbContext CreateContext(IServiceProvider serviceProvider) => new DbContext(serviceProvider, CreateOptions()); + public DbContext CreateContext(IServiceProvider serviceProvider) + => new DbContext(CreateOptions(serviceProvider)); - public DbContext CreateContext(IModel model) => new DbContext(CreateServiceProvider(), CreateOptions(model)); + public DbContext CreateContext(IModel model) + => new DbContext(CreateOptions(model, CreateServiceProvider())); - public DbContext CreateContext(DbContextOptions options) => new DbContext(CreateServiceProvider(), options); + public DbContext CreateContext(DbContextOptions options) + => new DbContext(new DbContextOptionsBuilder(options).UseInternalServiceProvider(CreateServiceProvider()).Options); - public DbContext CreateContext() => new DbContext(CreateServiceProvider(), CreateOptions()); + public DbContext CreateContext() + => new DbContext(CreateOptions(CreateServiceProvider())); public DbContext CreateContext(IServiceCollection customServices, IModel model) - => new DbContext(CreateServiceProvider(customServices), CreateOptions(model)); + => new DbContext(CreateOptions(model, CreateServiceProvider(customServices))); public DbContext CreateContext(IServiceCollection customServices, DbContextOptions options) - => new DbContext(CreateServiceProvider(customServices), options); + => new DbContext(new DbContextOptionsBuilder(options).UseInternalServiceProvider(CreateServiceProvider(customServices)).Options); public DbContext CreateContext(IServiceCollection customServices) - => new DbContext(CreateServiceProvider(customServices), CreateOptions()); + => new DbContext(CreateOptions(CreateServiceProvider(customServices))); public IServiceProvider CreateContextServices(IServiceProvider serviceProvider, IModel model) => ((IInfrastructure)CreateContext(serviceProvider, model)).Instance; diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ChangedChangingMonsterContext.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ChangedChangingMonsterContext.cs index 4b038286025..5f928aa3a2f 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ChangedChangingMonsterContext.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ChangedChangingMonsterContext.cs @@ -23,8 +23,8 @@ public class ChangedChangingMonsterContext : MonsterContext< ChangedChangingMonsterContext.Computer, ChangedChangingMonsterContext.ComputerDetail, ChangedChangingMonsterContext.Driver, ChangedChangingMonsterContext.License> { - public ChangedChangingMonsterContext(IServiceProvider serviceProvider, DbContextOptions options, Action onModelCreating) - : base(serviceProvider, options, onModelCreating) + public ChangedChangingMonsterContext(DbContextOptions options, Action onModelCreating) + : base(options, onModelCreating) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ChangedOnlyMonsterContext.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ChangedOnlyMonsterContext.cs index fb4256ced5f..c1bc7e4bb15 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ChangedOnlyMonsterContext.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ChangedOnlyMonsterContext.cs @@ -23,8 +23,8 @@ public class ChangedOnlyMonsterContext : MonsterContext< ChangedOnlyMonsterContext.Computer, ChangedOnlyMonsterContext.ComputerDetail, ChangedOnlyMonsterContext.Driver, ChangedOnlyMonsterContext.License> { - public ChangedOnlyMonsterContext(IServiceProvider serviceProvider, DbContextOptions options, Action onModelCreating) - : base(serviceProvider, options, onModelCreating) + public ChangedOnlyMonsterContext(DbContextOptions options, Action onModelCreating) + : base(options, onModelCreating) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ComplexNavigationsModel/ComplexNavigationsContext.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ComplexNavigationsModel/ComplexNavigationsContext.cs index 2700cc75646..fc4ba96aaf4 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ComplexNavigationsModel/ComplexNavigationsContext.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ComplexNavigationsModel/ComplexNavigationsContext.cs @@ -10,8 +10,8 @@ public class ComplexNavigationsContext : DbContext { public static readonly string StoreName = "ComplexNavigations"; - public ComplexNavigationsContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public ComplexNavigationsContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ConcurrencyModel/F1Context.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ConcurrencyModel/F1Context.cs index f0f0f68ee8b..057ca486058 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ConcurrencyModel/F1Context.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/ConcurrencyModel/F1Context.cs @@ -8,8 +8,8 @@ namespace Microsoft.EntityFrameworkCore.FunctionalTests.TestModels.ConcurrencyMo { public class F1Context : DbContext { - public F1Context(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public F1Context(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/GearsOfWarModel/GearsOfWarContext.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/GearsOfWarModel/GearsOfWarContext.cs index 2cdb2341b22..2700e951b90 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/GearsOfWarModel/GearsOfWarContext.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/GearsOfWarModel/GearsOfWarContext.cs @@ -10,8 +10,8 @@ public class GearsOfWarContext : DbContext { public static readonly string StoreName = "GearsOfWar"; - public GearsOfWarContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public GearsOfWarContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/Inheritance/InheritanceContext.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/Inheritance/InheritanceContext.cs index c2199cae46e..8900fb75339 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/Inheritance/InheritanceContext.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/Inheritance/InheritanceContext.cs @@ -10,8 +10,8 @@ public class InheritanceContext : DbContext { public static readonly string StoreName = "Inheritance"; - public InheritanceContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public InheritanceContext(DbContextOptions options) + : base(options) { } } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/InheritanceRelationships/InheritanceRelationshipsContext.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/InheritanceRelationships/InheritanceRelationshipsContext.cs index b7c2cb95875..a8412e79109 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/InheritanceRelationships/InheritanceRelationshipsContext.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/InheritanceRelationships/InheritanceRelationshipsContext.cs @@ -10,8 +10,8 @@ public class InheritanceRelationshipsContext : DbContext { public static readonly string StoreName = "InheritanceRelationships"; - public InheritanceRelationshipsContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public InheritanceRelationshipsContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/MonsterContext.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/MonsterContext.cs index 1dd8aa8301c..cc1647c7b8e 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/MonsterContext.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/MonsterContext.cs @@ -9,8 +9,8 @@ namespace Microsoft.EntityFrameworkCore.FunctionalTests.TestModels { public abstract class MonsterContext : DbContext { - protected MonsterContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + protected MonsterContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/MonsterContext`.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/MonsterContext`.cs index e3154c2cfdb..206e7e11a53 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/MonsterContext`.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/MonsterContext`.cs @@ -48,8 +48,8 @@ public class MonsterContext< { private readonly Action _onModelCreating; - public MonsterContext(IServiceProvider serviceProvider, DbContextOptions options, Action onModelCreating) - : base(serviceProvider, options) + public MonsterContext(DbContextOptions options, Action onModelCreating) + : base(options) { _onModelCreating = onModelCreating; } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/Northwind/NorthwindContext.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/Northwind/NorthwindContext.cs index 81aa59ffa2d..0494b4ca71d 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/Northwind/NorthwindContext.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/Northwind/NorthwindContext.cs @@ -10,8 +10,8 @@ public class NorthwindContext : DbContext { public static readonly string StoreName = "Northwind"; - public NorthwindContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public NorthwindContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/NullSemanticsModel/NullSemanticsContext.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/NullSemanticsModel/NullSemanticsContext.cs index a0bb276fb2d..7f974749144 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/NullSemanticsModel/NullSemanticsContext.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/NullSemanticsModel/NullSemanticsContext.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.EntityFrameworkCore.Infrastructure; namespace Microsoft.EntityFrameworkCore.FunctionalTests.TestModels.NullSemanticsModel @@ -10,8 +9,8 @@ public class NullSemanticsContext : DbContext { public static readonly string StoreName = "NullSemantics"; - public NullSemanticsContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public NullSemanticsContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/SnapshotMonsterContext.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/SnapshotMonsterContext.cs index f48365c05d4..6258b005b66 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/SnapshotMonsterContext.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/SnapshotMonsterContext.cs @@ -20,8 +20,8 @@ public class SnapshotMonsterContext : MonsterContext< SnapshotMonsterContext.Computer, SnapshotMonsterContext.ComputerDetail, SnapshotMonsterContext.Driver, SnapshotMonsterContext.License> { - public SnapshotMonsterContext(IServiceProvider serviceProvider, DbContextOptions options, Action onModelCreating) - : base(serviceProvider, options, onModelCreating) + public SnapshotMonsterContext(DbContextOptions options, Action onModelCreating) + : base(options, onModelCreating) { } diff --git a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/UpdatesModel/UpdatesContext.cs b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/UpdatesModel/UpdatesContext.cs index baee864594d..0075205b54f 100644 --- a/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/UpdatesModel/UpdatesContext.cs +++ b/test/Microsoft.EntityFrameworkCore.FunctionalTests/TestModels/UpdatesModel/UpdatesContext.cs @@ -11,10 +11,8 @@ public class UpdatesContext : DbContext public DbSet Categories { get; set; } public DbSet Products { get; set; } - public UpdatesContext( - IServiceProvider serviceProvider, - DbContextOptions options) - : base(serviceProvider, options) + public UpdatesContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/BuiltInDataTypesInMemoryFixture.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/BuiltInDataTypesInMemoryFixture.cs index 3f20352dcef..654f1a4331e 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/BuiltInDataTypesInMemoryFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/BuiltInDataTypesInMemoryFixture.cs @@ -10,30 +10,27 @@ namespace Microsoft.EntityFrameworkCore.InMemory.FunctionalTests { public class BuiltInDataTypesInMemoryFixture : BuiltInDataTypesFixtureBase { - private readonly IServiceProvider _serviceProvider; private readonly DbContextOptions _options; private readonly InMemoryTestStore _testStore; public BuiltInDataTypesInMemoryFixture() { _testStore = new InMemoryTestStore(); - _serviceProvider = new ServiceCollection() + var serviceProvider = new ServiceCollection() .AddEntityFramework() .AddInMemoryDatabase() .AddSingleton(TestInMemoryModelSource.GetFactory(OnModelCreating)) .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(serviceProvider) + .Options; } - public override DbContext CreateContext() => new DbContext(_serviceProvider, _options); + public override DbContext CreateContext() => new DbContext(_options); - public override void Dispose() - { - _testStore.Dispose(); - } + public override void Dispose() => _testStore.Dispose(); public override bool SupportsBinaryKeys => false; diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/ComplexNavigationsQueryInMemoryFixture.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/ComplexNavigationsQueryInMemoryFixture.cs index dc068829ffc..3086582ff21 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/ComplexNavigationsQueryInMemoryFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/ComplexNavigationsQueryInMemoryFixture.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.EntityFrameworkCore.FunctionalTests; using Microsoft.EntityFrameworkCore.FunctionalTests.TestModels.ComplexNavigationsModel; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -13,30 +12,26 @@ public class ComplexNavigationsQueryInMemoryFixture : ComplexNavigationsQueryFix { public const string DatabaseName = "InMemoryQueryTest"; - private readonly IServiceProvider _serviceProvider; private readonly DbContextOptions _options; public ComplexNavigationsQueryInMemoryFixture() { - _serviceProvider - = new ServiceCollection() - .AddEntityFramework() - .AddInMemoryDatabase() - .AddSingleton(TestInMemoryModelSource.GetFactory(OnModelCreating)) - .BuildServiceProvider(); - - var optionsBuilder = new DbContextOptionsBuilder(); - - optionsBuilder.UseInMemoryDatabase(); - - _options = optionsBuilder.Options; + var serviceProvider = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .AddSingleton(TestInMemoryModelSource.GetFactory(OnModelCreating)) + .BuildServiceProvider(); + + _options = new DbContextOptionsBuilder() + .UseInternalServiceProvider(serviceProvider) + .UseInMemoryDatabase().Options; } public override InMemoryTestStore CreateTestStore() { return InMemoryTestStore.GetOrCreateShared(DatabaseName, () => { - using (var context = new ComplexNavigationsContext(_serviceProvider, _options)) + using (var context = new ComplexNavigationsContext(_options)) { ComplexNavigationsModelInitializer.Seed(context); } @@ -45,7 +40,7 @@ public override InMemoryTestStore CreateTestStore() public override ComplexNavigationsContext CreateContext(InMemoryTestStore _) { - var context = new ComplexNavigationsContext(_serviceProvider, _options); + var context = new ComplexNavigationsContext(_options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/CompositeKeyEndToEndTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/CompositeKeyEndToEndTest.cs index 6d1257e6aca..6f96e958227 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/CompositeKeyEndToEndTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/CompositeKeyEndToEndTest.cs @@ -171,9 +171,11 @@ public async Task Only_one_part_of_a_composite_key_needs_to_vary_for_uniquness() private class BronieContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public BronieContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Pegasuses { get; set; } @@ -181,7 +183,7 @@ public BronieContext(IServiceProvider serviceProvider) public DbSet EarthPonies { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseInMemoryDatabase(); + => optionsBuilder.UseInMemoryDatabase().UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/ConfigPatternsInMemoryTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/ConfigPatternsInMemoryTest.cs index 7f9ad05704e..fefa6cc8e33 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/ConfigPatternsInMemoryTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/ConfigPatternsInMemoryTest.cs @@ -107,33 +107,35 @@ public void Can_save_and_query_with_explicit_services_and_OnConfiguring() private class ExplicitServicesImplicitConfigBlogContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public ExplicitServicesImplicitConfigBlogContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Blogs { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseInMemoryDatabase(); + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseInternalServiceProvider(_serviceProvider).UseInMemoryDatabase(); } [Fact] public void Can_save_and_query_with_explicit_services_and_explicit_config() { - var services = new ServiceCollection(); - services.AddEntityFramework().AddInMemoryDatabase(); - var serviceProvider = services.BuildServiceProvider(); - - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase().BuildServiceProvider()); - using (var context = new ExplicitServicesAndConfigBlogContext(serviceProvider, optionsBuilder.Options)) + using (var context = new ExplicitServicesAndConfigBlogContext(optionsBuilder.Options)) { context.Blogs.Add(new Blog { Name = "The Waffle Cart" }); context.SaveChanges(); } - using (var context = new ExplicitServicesAndConfigBlogContext(serviceProvider, optionsBuilder.Options)) + using (var context = new ExplicitServicesAndConfigBlogContext(optionsBuilder.Options)) { var blog = context.Blogs.SingleOrDefault(); @@ -149,8 +151,8 @@ public void Can_save_and_query_with_explicit_services_and_explicit_config() private class ExplicitServicesAndConfigBlogContext : DbContext { - public ExplicitServicesAndConfigBlogContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public ExplicitServicesAndConfigBlogContext(DbContextOptions options) + : base(options) { } @@ -185,7 +187,7 @@ public void Throws_on_attempt_to_use_store_with_no_store_services() var serviceProvider = serviceCollection.BuildServiceProvider(); Assert.Equal( - CoreStrings.NoProviderServices, + CoreStrings.NoProviderConfigured, Assert.Throws(() => { using (var context = new ImplicitConfigButNoServicesBlogContext(serviceProvider)) @@ -198,14 +200,17 @@ public void Throws_on_attempt_to_use_store_with_no_store_services() private class ImplicitConfigButNoServicesBlogContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public ImplicitConfigButNoServicesBlogContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Blogs { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseInMemoryDatabase(); + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseInMemoryDatabase().UseInternalServiceProvider(_serviceProvider); } [Fact] @@ -247,14 +252,16 @@ public void Test() private class InjectContextBlogContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public InjectContextBlogContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; Assert.NotNull(serviceProvider); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseInMemoryDatabase(); + => optionsBuilder.UseInMemoryDatabase().UseInternalServiceProvider(_serviceProvider); public DbSet Blogs { get; set; } } @@ -262,17 +269,16 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) [Fact] public void Can_register_context_and_configuration_with_DI_container_and_have_both_injected() { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase(); - var services = new ServiceCollection(); - services.AddTransient() + var serviceProvider = new ServiceCollection() + .AddTransient() .AddTransient() - .AddSingleton(optionsBuilder.Options) + .AddSingleton(p => optionsBuilder.UseInternalServiceProvider(p).Options) .AddEntityFramework() - .AddInMemoryDatabase(); - - var serviceProvider = services.BuildServiceProvider(); + .AddInMemoryDatabase() + .BuildServiceProvider(); serviceProvider.GetRequiredService().Test(); } @@ -302,10 +308,9 @@ public void Test() private class InjectContextAndConfigurationBlogContext : DbContext { - public InjectContextAndConfigurationBlogContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public InjectContextAndConfigurationBlogContext(DbContextOptions options) + : base(options) { - Assert.NotNull(serviceProvider); Assert.NotNull(options); } @@ -370,23 +375,22 @@ public InjectConfigurationBlogContext(DbContextOptions options) [Fact] public void Can_inject_different_configurations_into_different_contexts() { - var blogOptions = new DbContextOptionsBuilder(); - blogOptions.UseInMemoryDatabase(); + var blogOptions = new DbContextOptionsBuilder() + .UseInMemoryDatabase(); - var accountOptions = new DbContextOptionsBuilder(); - accountOptions.UseInMemoryDatabase(); + var accountOptions = new DbContextOptionsBuilder() + .UseInMemoryDatabase(); - var services = new ServiceCollection(); - services.AddTransient() + var serviceProvider = new ServiceCollection() + .AddTransient() .AddTransient() .AddTransient() .AddTransient() - .AddSingleton(blogOptions.Options) - .AddSingleton(accountOptions.Options) + .AddSingleton(p => blogOptions.UseInternalServiceProvider(p).Options) + .AddSingleton(p => accountOptions.UseInternalServiceProvider(p).Options) .AddEntityFramework() - .AddInMemoryDatabase(); - - var serviceProvider = services.BuildServiceProvider(); + .AddInMemoryDatabase() + .BuildServiceProvider(); serviceProvider.GetRequiredService().Test(); serviceProvider.GetRequiredService().Test(); @@ -446,10 +450,9 @@ public void Test() private class InjectDifferentConfigurationsBlogContext : DbContext { - public InjectDifferentConfigurationsBlogContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public InjectDifferentConfigurationsBlogContext(DbContextOptions options) + : base(options) { - Assert.NotNull(serviceProvider); Assert.NotNull(options); } @@ -458,10 +461,9 @@ public InjectDifferentConfigurationsBlogContext(IServiceProvider serviceProvider private class InjectDifferentConfigurationsAccountContext : DbContext { - public InjectDifferentConfigurationsAccountContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public InjectDifferentConfigurationsAccountContext(DbContextOptions options) + : base(options) { - Assert.NotNull(serviceProvider); Assert.NotNull(options); } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/DataAnnotationInMemoryFixture.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/DataAnnotationInMemoryFixture.cs index 1bd5425dc29..b1ff311b5f1 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/DataAnnotationInMemoryFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/DataAnnotationInMemoryFixture.cs @@ -26,10 +26,11 @@ public override InMemoryTestStore CreateTestStore() { return InMemoryTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); - using (var context = new DataAnnotationContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new DataAnnotationContext(optionsBuilder.Options)) { context.Database.EnsureDeleted(); if (context.Database.EnsureCreated()) @@ -41,13 +42,8 @@ public override InMemoryTestStore CreateTestStore() } public override DataAnnotationContext CreateContext(InMemoryTestStore testStore) - { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - - var context = new DataAnnotationContext(_serviceProvider, optionsBuilder.Options); - - return context; - } + => new DataAnnotationContext(new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider).Options); } } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/DatabaseInMemoryTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/DatabaseInMemoryTest.cs index 174c66a12e1..be31548f7f0 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/DatabaseInMemoryTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/DatabaseInMemoryTest.cs @@ -23,13 +23,15 @@ public async Task Can_add_update_delete_end_to_end() .AddSingleton(TestFileLogger.Factory) .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder() - .UseModel(model); - optionsBuilder.UseInMemoryDatabase(); + var options = new DbContextOptionsBuilder() + .UseModel(model) + .UseInternalServiceProvider(serviceProvider) + .UseInMemoryDatabase() + .Options; var customer = new Customer { Id = 42, Name = "Theon" }; - using (var context = new DbContext(serviceProvider, optionsBuilder.Options)) + using (var context = new DbContext(options)) { context.Add(customer); @@ -38,7 +40,7 @@ public async Task Can_add_update_delete_end_to_end() customer.Name = "Changed!"; } - using (var context = new DbContext(serviceProvider, optionsBuilder.Options)) + using (var context = new DbContext(options)) { var customerFromStore = context.Set().Single(); @@ -46,7 +48,7 @@ public async Task Can_add_update_delete_end_to_end() Assert.Equal("Theon", customerFromStore.Name); } - using (var context = new DbContext(serviceProvider, optionsBuilder.Options)) + using (var context = new DbContext(options)) { customer.Name = "Theon Greyjoy"; context.Update(customer); @@ -54,7 +56,7 @@ public async Task Can_add_update_delete_end_to_end() await context.SaveChangesAsync(); } - using (var context = new DbContext(serviceProvider, optionsBuilder.Options)) + using (var context = new DbContext(options)) { var customerFromStore = context.Set().Single(); @@ -62,14 +64,14 @@ public async Task Can_add_update_delete_end_to_end() Assert.Equal("Theon Greyjoy", customerFromStore.Name); } - using (var context = new DbContext(serviceProvider, optionsBuilder.Options)) + using (var context = new DbContext(options)) { context.Remove(customer); await context.SaveChangesAsync(); } - using (var context = new DbContext(serviceProvider, optionsBuilder.Options)) + using (var context = new DbContext(options)) { Assert.Equal(0, context.Set().Count()); } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/EndToEndTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/EndToEndTest.cs index e17159deee4..b2884c0170b 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/EndToEndTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/EndToEndTest.cs @@ -36,11 +36,12 @@ private void Can_add_update_delete_end_to_end() entityType.GetOrSetPrimaryKey(idProperty); var optionsBuilder = new DbContextOptionsBuilder() - .UseModel(model); - optionsBuilder.UseInMemoryDatabase(); + .UseModel(model) + .UseInMemoryDatabase() + .UseInternalServiceProvider(_fixture.ServiceProvider); T entity; - using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new DbContext(optionsBuilder.Options)) { var entry = context.ChangeTracker.GetInfrastructure().GetOrCreateEntry(new T()); entity = (T)entry.Entity; @@ -53,7 +54,7 @@ private void Can_add_update_delete_end_to_end() context.SaveChanges(); } - using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new DbContext(optionsBuilder.Options)) { var entityFromStore = context.Set().Single(); var entityEntry = context.Entry(entityFromStore); @@ -69,7 +70,7 @@ private void Can_add_update_delete_end_to_end() context.SaveChanges(); } - using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new DbContext(optionsBuilder.Options)) { var entityFromStore = context.Set().Single(); var entry = context.Entry(entityFromStore); @@ -81,7 +82,7 @@ private void Can_add_update_delete_end_to_end() context.SaveChanges(); } - using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new DbContext(optionsBuilder.Options)) { Assert.Equal(0, context.Set().Count()); } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/GearsOfWarQueryInMemoryFixture.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/GearsOfWarQueryInMemoryFixture.cs index b472f10121c..009da0bd768 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/GearsOfWarQueryInMemoryFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/GearsOfWarQueryInMemoryFixture.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.EntityFrameworkCore.FunctionalTests; using Microsoft.EntityFrameworkCore.FunctionalTests.TestModels.GearsOfWarModel; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -13,21 +12,19 @@ public class GearsOfWarQueryInMemoryFixture : GearsOfWarQueryFixtureBase { - using (var context = new GearsOfWarContext(_serviceProvider, _options)) + using (var context = new GearsOfWarContext(_options)) { GearsOfWarModelInitializer.Seed(context); } @@ -45,7 +42,7 @@ public override InMemoryTestStore CreateTestStore() public override GearsOfWarContext CreateContext(InMemoryTestStore _) { - var context = new GearsOfWarContext(_serviceProvider, _options); + var context = new GearsOfWarContext(_options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/GraphUpdatesInMemoryTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/GraphUpdatesInMemoryTest.cs index c72794cfd3b..c97217077f8 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/GraphUpdatesInMemoryTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/GraphUpdatesInMemoryTest.cs @@ -185,12 +185,9 @@ public override InMemoryTestStore CreateTestStore() } public override DbContext CreateContext(InMemoryTestStore testStore) - { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - - return new GraphUpdatesContext(_serviceProvider, optionsBuilder.Options); - } + => new GraphUpdatesContext(new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider).Options); public class InMemoryGraphUpdatesTestStore : InMemoryTestStore { diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/GuidValueGeneratorEndToEndTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/GuidValueGeneratorEndToEndTest.cs index f24d545cbb0..c267a10f66d 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/GuidValueGeneratorEndToEndTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/GuidValueGeneratorEndToEndTest.cs @@ -49,13 +49,15 @@ public async Task Can_use_GUIDs_end_to_end_async() private class BronieContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public BronieContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseInMemoryDatabase(); + => optionsBuilder.UseInMemoryDatabase().UseInternalServiceProvider(_serviceProvider); public DbSet Pegasuses { get; set; } } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/InheritanceInMemoryFixture.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/InheritanceInMemoryFixture.cs index 2dcdfd6b345..5287dee8400 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/InheritanceInMemoryFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/InheritanceInMemoryFixture.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.EntityFrameworkCore.FunctionalTests; using Microsoft.EntityFrameworkCore.FunctionalTests.TestModels.Inheritance; using Microsoft.Extensions.DependencyInjection; @@ -11,18 +10,16 @@ namespace Microsoft.EntityFrameworkCore.InMemory.FunctionalTests public class InheritanceInMemoryFixture : InheritanceFixtureBase { private readonly DbContextOptionsBuilder _optionsBuilder = new DbContextOptionsBuilder(); - private readonly IServiceProvider _serviceProvider; public InheritanceInMemoryFixture() { - _serviceProvider - = new ServiceCollection() - .AddEntityFramework() - .AddInMemoryDatabase() - .AddSingleton(TestInMemoryModelSource.GetFactory(OnModelCreating)) - .BuildServiceProvider(); + var serviceProvider = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .AddSingleton(TestInMemoryModelSource.GetFactory(OnModelCreating)) + .BuildServiceProvider(); - _optionsBuilder.UseInMemoryDatabase(); + _optionsBuilder.UseInMemoryDatabase().UseInternalServiceProvider(serviceProvider); using (var context = CreateContext()) { @@ -30,9 +27,7 @@ public InheritanceInMemoryFixture() } } - public override InheritanceContext CreateContext() - { - return new InheritanceContext(_serviceProvider, _optionsBuilder.Options); - } + public override InheritanceContext CreateContext() + => new InheritanceContext(_optionsBuilder.Options); } } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/IntegerGeneratorEndToEndInMemoryTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/IntegerGeneratorEndToEndInMemoryTest.cs index fbd6a728700..03c9d722440 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/IntegerGeneratorEndToEndInMemoryTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/IntegerGeneratorEndToEndInMemoryTest.cs @@ -127,13 +127,15 @@ public async Task Can_use_sequence_end_to_end_from_multiple_contexts_concurrentl private class BronieContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public BronieContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseInMemoryDatabase(); + => optionsBuilder.UseInMemoryDatabase().UseInternalServiceProvider(_serviceProvider); public DbSet Pegasuses { get; set; } } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/MusicStoreQueryTests.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/MusicStoreQueryTests.cs index 586a9768de7..29146506b09 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/MusicStoreQueryTests.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/MusicStoreQueryTests.cs @@ -24,10 +24,11 @@ var serviceProvider .AddInMemoryDatabase() .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(serviceProvider); - using (var db = new MusicStoreContext(serviceProvider, optionsBuilder.Options)) + using (var db = new MusicStoreContext(optionsBuilder.Options)) { var albums = GetAlbums("~/Images/placeholder.png", Genres, Artists); @@ -38,7 +39,7 @@ var serviceProvider db.SaveChanges(); } - using (var db = new MusicStoreContext(serviceProvider, optionsBuilder.Options)) + using (var db = new MusicStoreContext(optionsBuilder.Options)) { var q = from album in db.Albums join genre in db.Genres on album.GenreId equals genre.GenreId @@ -71,8 +72,8 @@ join artist in db.Artists on album.ArtistId equals artist.ArtistId public class MusicStoreContext : DbContext { - public MusicStoreContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public MusicStoreContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/NorthwindQueryInMemoryFixture.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/NorthwindQueryInMemoryFixture.cs index 473ce21dc90..1153d8edf39 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/NorthwindQueryInMemoryFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/NorthwindQueryInMemoryFixture.cs @@ -14,23 +14,21 @@ namespace Microsoft.EntityFrameworkCore.InMemory.FunctionalTests public class NorthwindQueryInMemoryFixture : NorthwindQueryFixtureBase { private readonly DbContextOptions _options; - private readonly IServiceProvider _serviceProvider; private readonly TestLoggerFactory _testLoggerFactory = new TestLoggerFactory(); public NorthwindQueryInMemoryFixture() { - _serviceProvider - = new ServiceCollection() - .AddEntityFramework() - .AddInMemoryDatabase() - .AddSingleton(TestInMemoryModelSource.GetFactory(OnModelCreating)) - .AddSingleton(_testLoggerFactory) - .BuildServiceProvider(); - - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - _options = optionsBuilder.Options; + var serviceProvider = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .AddSingleton(TestInMemoryModelSource.GetFactory(OnModelCreating)) + .AddSingleton(_testLoggerFactory) + .BuildServiceProvider(); + + _options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(serviceProvider).Options; using (var context = CreateContext()) { @@ -39,7 +37,7 @@ public NorthwindQueryInMemoryFixture() } public override NorthwindContext CreateContext() - => new NorthwindContext(_serviceProvider, _options); + => new NorthwindContext(_options); } public class TestLoggerFactory : ILoggerFactory diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/NotificationEntitiesInMemoryTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/NotificationEntitiesInMemoryTest.cs index bcc4b54763a..690f82647f4 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/NotificationEntitiesInMemoryTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/NotificationEntitiesInMemoryTest.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.EntityFrameworkCore.FunctionalTests; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; @@ -18,26 +17,25 @@ public NotificationEntitiesInMemoryTest(NotificationEntitiesInMemoryFixture fixt public class NotificationEntitiesInMemoryFixture : NotificationEntitiesFixtureBase { - private readonly IServiceProvider _serviceProvider; private readonly DbContextOptions _options; public NotificationEntitiesInMemoryFixture() { - _serviceProvider = new ServiceCollection() + var serviceProvider = new ServiceCollection() .AddEntityFramework() .AddInMemoryDatabase() .AddSingleton(TestInMemoryModelSource.GetFactory(OnModelCreating)) .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(serviceProvider).Options; EnsureCreated(); } public override DbContext CreateContext() - => new DbContext(_serviceProvider, _options); + => new DbContext(_options); } } } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/NullKeysInMemoryTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/NullKeysInMemoryTest.cs index 377546d3e49..331fdf2c3f1 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/NullKeysInMemoryTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/NullKeysInMemoryTest.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.EntityFrameworkCore.FunctionalTests; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; @@ -17,28 +16,25 @@ public NullKeysInMemoryTest(NullKeysInMemoryFixture fixture) public class NullKeysInMemoryFixture : NullKeysFixtureBase { - private readonly IServiceProvider _serviceProvider; private readonly DbContextOptions _options; public NullKeysInMemoryFixture() { - _serviceProvider = new ServiceCollection() + var serviceProvider = new ServiceCollection() .AddEntityFramework() .AddInMemoryDatabase() .AddSingleton(TestInMemoryModelSource.GetFactory(OnModelCreating)) .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(serviceProvider).Options; EnsureCreated(); } - public override DbContext CreateContext() - { - return new DbContext(_serviceProvider, _options); - } + public override DbContext CreateContext() + => new DbContext(_options); } } } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/OneToOneQueryInMemoryFixture.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/OneToOneQueryInMemoryFixture.cs index 8fa47d07805..63052c8adad 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/OneToOneQueryInMemoryFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/OneToOneQueryInMemoryFixture.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.EntityFrameworkCore.FunctionalTests; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; @@ -11,27 +10,25 @@ namespace Microsoft.EntityFrameworkCore.InMemory.FunctionalTests public class OneToOneQueryInMemoryFixture : OneToOneQueryFixtureBase { private readonly DbContextOptions _options; - private readonly IServiceProvider _serviceProvider; public OneToOneQueryInMemoryFixture() { - _serviceProvider - = new ServiceCollection() - .AddEntityFramework() - .AddInMemoryDatabase() - .AddSingleton(TestInMemoryModelSource.GetFactory(OnModelCreating)) - .BuildServiceProvider(); + var serviceProvider = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .AddSingleton(TestInMemoryModelSource.GetFactory(OnModelCreating)) + .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(serviceProvider).Options; - using (var context = new DbContext(_serviceProvider, _options)) + using (var context = new DbContext(_options)) { AddTestData(context); } } - public DbContext CreateContext() => new DbContext(_serviceProvider, _options); + public DbContext CreateContext() => new DbContext(_options); } } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/ShadowStateUpdateTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/ShadowStateUpdateTest.cs index 15c5ea6a1ea..a0a5f12f9be 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/ShadowStateUpdateTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/ShadowStateUpdateTest.cs @@ -22,12 +22,14 @@ public async Task Can_add_update_delete_end_to_end_using_partial_shadow_state() customerType.GetOrSetPrimaryKey(property1); customerType.AddProperty("Name", typeof(string)); - var optionsBuilder = new DbContextOptionsBuilder().UseModel(model); - optionsBuilder.UseInMemoryDatabase(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseModel(model) + .UseInMemoryDatabase() + .UseInternalServiceProvider(_fixture.ServiceProvider); var customer = new Customer { Id = 42 }; - using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new DbContext(optionsBuilder.Options)) { context.Add(customer); @@ -40,7 +42,7 @@ public async Task Can_add_update_delete_end_to_end_using_partial_shadow_state() customerEntry[customerType.FindProperty("Name")] = "Changed!"; } - using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new DbContext(optionsBuilder.Options)) { var customerFromStore = context.Set().Single(); @@ -50,7 +52,7 @@ public async Task Can_add_update_delete_end_to_end_using_partial_shadow_state() (string)context.Entry(customerFromStore).Property("Name").CurrentValue); } - using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new DbContext(optionsBuilder.Options)) { var customerEntry = context.Entry(customer).GetInfrastructure(); customerEntry[customerType.FindProperty("Name")] = "Daenerys Targaryen"; @@ -60,7 +62,7 @@ public async Task Can_add_update_delete_end_to_end_using_partial_shadow_state() await context.SaveChangesAsync(); } - using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new DbContext(optionsBuilder.Options)) { var customerFromStore = context.Set().Single(); @@ -70,14 +72,14 @@ public async Task Can_add_update_delete_end_to_end_using_partial_shadow_state() (string)context.Entry(customerFromStore).Property("Name").CurrentValue); } - using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new DbContext(optionsBuilder.Options)) { context.Remove(customer); await context.SaveChangesAsync(); } - using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new DbContext(optionsBuilder.Options)) { Assert.Equal(0, context.Set().Count()); } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/StoreGeneratedInMemoryTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/StoreGeneratedInMemoryTest.cs index f12f55d8168..0aa7bb3d5b2 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/StoreGeneratedInMemoryTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/StoreGeneratedInMemoryTest.cs @@ -185,10 +185,11 @@ public override InMemoryTestStore CreateTestStore() { return InMemoryTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); - using (var context = new StoreGeneratedContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new StoreGeneratedContext(optionsBuilder.Options)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); @@ -198,10 +199,11 @@ public override InMemoryTestStore CreateTestStore() public override DbContext CreateContext(InMemoryTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); - var context = new StoreGeneratedContext(_serviceProvider, optionsBuilder.Options); + var context = new StoreGeneratedContext(optionsBuilder.Options); return context; } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/UpdatesInMemoryFixture.cs b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/UpdatesInMemoryFixture.cs index a7d41346b7c..10e7d547ead 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/UpdatesInMemoryFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.FunctionalTests/UpdatesInMemoryFixture.cs @@ -21,15 +21,16 @@ public UpdatesInMemoryFixture() .AddInMemoryDatabase() .BuildServiceProvider(); - _optionsBuilder = new DbContextOptionsBuilder(); - _optionsBuilder.UseInMemoryDatabase(); + _optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); } public override InMemoryTestStore CreateTestStore() => InMemoryTestStore.CreateScratch( () => { - using (var context = new UpdatesContext(_serviceProvider, _optionsBuilder.Options)) + using (var context = new UpdatesContext(_optionsBuilder.Options)) { UpdatesModelInitializer.Seed(context); } @@ -39,9 +40,7 @@ public override InMemoryTestStore CreateTestStore() _serviceProvider.GetRequiredService().Clear(); }); - public override UpdatesContext CreateContext(InMemoryTestStore testStore) - { - return new UpdatesContext(_serviceProvider, _optionsBuilder.Options); - } + public override UpdatesContext CreateContext(InMemoryTestStore testStore) + => new UpdatesContext(_optionsBuilder.Options); } } diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.Tests/InMemoryDbContextOptionsExtensionsTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.Tests/InMemoryDbContextOptionsExtensionsTest.cs index 82ef9e421ee..0e6398ef648 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.Tests/InMemoryDbContextOptionsExtensionsTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.Tests/InMemoryDbContextOptionsExtensionsTest.cs @@ -13,7 +13,7 @@ public class InMemoryDbContextOptionsExtensionsTest public void Can_add_extension_with_transactions_ignored() { var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase().IgnoreTransactions(); + optionsBuilder.UseInMemoryDatabase(b => b.IgnoreTransactions()); var extension = optionsBuilder.Options.Extensions.OfType().Single(); diff --git a/test/Microsoft.EntityFrameworkCore.InMemory.Tests/InMemoryTransactionManagerTest.cs b/test/Microsoft.EntityFrameworkCore.InMemory.Tests/InMemoryTransactionManagerTest.cs index d3b22353f94..49cf0c241e5 100644 --- a/test/Microsoft.EntityFrameworkCore.InMemory.Tests/InMemoryTransactionManagerTest.cs +++ b/test/Microsoft.EntityFrameworkCore.InMemory.Tests/InMemoryTransactionManagerTest.cs @@ -70,9 +70,8 @@ public void Throws_on_RollbackTransaction() [Fact] public void Does_not_throw_on_BeginTransaction_when_transactions_ignored() { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase() - .IgnoreTransactions(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase(b => b.IgnoreTransactions()); var transactionManager = new InMemoryTransactionManager(optionsBuilder.Options); @@ -86,9 +85,8 @@ public void Does_not_throw_on_BeginTransaction_when_transactions_ignored() [Fact] public async Task Does_not_throw_on_BeginTransactionAsync_when_transactions_ignored() { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase() - .IgnoreTransactions(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase(b => b.IgnoreTransactions()); var transactionManager = new InMemoryTransactionManager(optionsBuilder.Options); @@ -102,9 +100,8 @@ public async Task Does_not_throw_on_BeginTransactionAsync_when_transactions_igno [Fact] public void Does_not_throw_on_CommitTransaction_when_transactions_ignored() { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase() - .IgnoreTransactions(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase(b => b.IgnoreTransactions()); var transactionManager = new InMemoryTransactionManager(optionsBuilder.Options); @@ -114,9 +111,8 @@ public void Does_not_throw_on_CommitTransaction_when_transactions_ignored() [Fact] public void Does_not_throw_on_RollbackTransaction_when_transactions_ignored() { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase() - .IgnoreTransactions(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase(b => b.IgnoreTransactions()); var transactionManager = new InMemoryTransactionManager(optionsBuilder.Options); diff --git a/test/Microsoft.EntityFrameworkCore.Microbenchmarks/Models/AdventureWorks/AdventureWorksContext.cs b/test/Microsoft.EntityFrameworkCore.Microbenchmarks/Models/AdventureWorks/AdventureWorksContext.cs index 163662e3a39..f20a3ffa244 100644 --- a/test/Microsoft.EntityFrameworkCore.Microbenchmarks/Models/AdventureWorks/AdventureWorksContext.cs +++ b/test/Microsoft.EntityFrameworkCore.Microbenchmarks/Models/AdventureWorks/AdventureWorksContext.cs @@ -10,6 +10,7 @@ namespace Microsoft.EntityFrameworkCore.Microbenchmarks.Models.AdventureWorks public class AdventureWorksContext : DbContext { private readonly string _connectionString; + private readonly IServiceProvider _serviceProvider; public AdventureWorksContext(string connectionString) { @@ -17,9 +18,9 @@ public AdventureWorksContext(string connectionString) } public AdventureWorksContext(string connectionString, IServiceProvider serviceProvider) - : base(serviceProvider) { _connectionString = connectionString; + _serviceProvider = serviceProvider; } public virtual DbSet
Address { get; set; } @@ -90,15 +91,11 @@ public AdventureWorksContext(string connectionString, IServiceProvider servicePr public virtual DbSet WorkOrder { get; set; } public virtual DbSet WorkOrderRouting { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder options) - { - options.UseSqlServer(_connectionString); - } + protected override void OnConfiguring(DbContextOptionsBuilder options) + => options.UseSqlServer(_connectionString).UseInternalServiceProvider(_serviceProvider); - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + protected override void OnModelCreating(ModelBuilder modelBuilder) + => ConfigureModel(modelBuilder); public static void ConfigureModel(ModelBuilder modelBuilder) { diff --git a/test/Microsoft.EntityFrameworkCore.Microbenchmarks/Models/Orders/OrdersContext.cs b/test/Microsoft.EntityFrameworkCore.Microbenchmarks/Models/Orders/OrdersContext.cs index a9a9f5ce5cf..c59cc8b530e 100644 --- a/test/Microsoft.EntityFrameworkCore.Microbenchmarks/Models/Orders/OrdersContext.cs +++ b/test/Microsoft.EntityFrameworkCore.Microbenchmarks/Models/Orders/OrdersContext.cs @@ -3,12 +3,12 @@ using System; using Microsoft.EntityFrameworkCore.Microbenchmarks.Core.Models.Orders; -using Microsoft.EntityFrameworkCore; namespace Microsoft.EntityFrameworkCore.Microbenchmarks.Models.Orders { public class OrdersContext : DbContext { + private readonly IServiceProvider _serviceProvider; private readonly string _connectionString; private readonly bool _disableBatching; @@ -19,8 +19,8 @@ public OrdersContext(string connectionString, bool disableBatching = false) } public OrdersContext(IServiceProvider serviceProvider, string connectionString, bool disableBatching = false) - : base(serviceProvider) { + _serviceProvider = serviceProvider; _connectionString = connectionString; _disableBatching = disableBatching; } @@ -31,13 +31,16 @@ public OrdersContext(IServiceProvider serviceProvider, string connectionString, public DbSet Products { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - var sqlBuilder = optionsBuilder.UseSqlServer(_connectionString); - - if (_disableBatching) - { - sqlBuilder.MaxBatchSize(1); - } - } + => optionsBuilder + .UseInternalServiceProvider(_serviceProvider) + .UseSqlServer( + _connectionString, + b => + { + if (_disableBatching) + { + b.MaxBatchSize(1); + } + }); } } diff --git a/test/Microsoft.EntityFrameworkCore.Relational.FunctionalTests/MigrationsFixtureBase.cs b/test/Microsoft.EntityFrameworkCore.Relational.FunctionalTests/MigrationsFixtureBase.cs index 6ef6ac69cf0..38686a8bbc6 100644 --- a/test/Microsoft.EntityFrameworkCore.Relational.FunctionalTests/MigrationsFixtureBase.cs +++ b/test/Microsoft.EntityFrameworkCore.Relational.FunctionalTests/MigrationsFixtureBase.cs @@ -15,8 +15,8 @@ public abstract class MigrationsFixtureBase public class MigrationsContext : DbContext { - public MigrationsContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public MigrationsContext(DbContextOptions options) + : base(options) { } } diff --git a/test/Microsoft.EntityFrameworkCore.Relational.FunctionalTests/RelationalTestHelpers.cs b/test/Microsoft.EntityFrameworkCore.Relational.FunctionalTests/RelationalTestHelpers.cs index e417fe956de..0756860916f 100644 --- a/test/Microsoft.EntityFrameworkCore.Relational.FunctionalTests/RelationalTestHelpers.cs +++ b/test/Microsoft.EntityFrameworkCore.Relational.FunctionalTests/RelationalTestHelpers.cs @@ -19,6 +19,6 @@ public override IServiceCollection AddProviderServices(IServiceCollection servic => services.AddInMemoryDatabase().AddRelational(); protected override void UseProviderOptions(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseInMemoryDatabase().IgnoreTransactions(); + => optionsBuilder.UseInMemoryDatabase(b => b.IgnoreTransactions()); } } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/BatchingTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/BatchingTest.cs index 612569195ec..e6b2bd6003f 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/BatchingTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/BatchingTest.cs @@ -87,7 +87,7 @@ public void Inserts_are_batched_correctly(bool clientPk, bool clientFk, bool cli private class BloggingContext : DbContext { public BloggingContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + : base(new DbContextOptionsBuilder(options).UseInternalServiceProvider(serviceProvider).Options) { } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/BuiltInDataTypesSqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/BuiltInDataTypesSqlServerFixture.cs index 0b215a3cd7c..3db48620cb0 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/BuiltInDataTypesSqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/BuiltInDataTypesSqlServerFixture.cs @@ -28,12 +28,12 @@ public BuiltInDataTypesSqlServerFixture() .AddSingleton(TestSqlServerModelSource.GetFactory(OnModelCreating)) .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(_testStore.Connection); + _options = new DbContextOptionsBuilder() + .UseSqlServer(_testStore.Connection) + .UseInternalServiceProvider(_serviceProvider) + .Options; - _options = optionsBuilder.Options; - - using (var context = new DbContext(_serviceProvider, _options)) + using (var context = new DbContext(_options)) { context.Database.EnsureCreated(); } @@ -41,7 +41,7 @@ public BuiltInDataTypesSqlServerFixture() public override DbContext CreateContext() { - var context = new DbContext(_serviceProvider, _options); + var context = new DbContext(_options); context.Database.UseTransaction(_testStore.Transaction); return context; } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/CommandConfigurationTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/CommandConfigurationTest.cs index 4ac444451c3..6c4826bba7f 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/CommandConfigurationTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/CommandConfigurationTest.cs @@ -108,17 +108,19 @@ where word.Contains(searchTerm) private class ChipsContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public ChipsContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Chips { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString(DatabaseName)); - } + => optionsBuilder + .UseSqlServer(SqlServerTestStore.CreateConnectionString(DatabaseName)) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -144,11 +146,8 @@ public ConfiguredChipsContext(IServiceProvider serviceProvider) } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer("Database=" + DatabaseName).CommandTimeout(77); - - base.OnConfiguring(optionsBuilder); - } + => base.OnConfiguring( + optionsBuilder.UseSqlServer("Database=" + DatabaseName, b => b.CommandTimeout(77))); } private static string Sql => TestSqlLoggerFactory.Sql; diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/CompiledQueryCacheKeyGeneratorTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/CompiledQueryCacheKeyGeneratorTest.cs index b0f9535ed05..0d82a243fcf 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/CompiledQueryCacheKeyGeneratorTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/CompiledQueryCacheKeyGeneratorTest.cs @@ -55,13 +55,14 @@ public QueryKeyCacheContext(bool rowNumberPaging, DbConnection connection) protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity(); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - var optionBuilder = optionsBuilder.UseSqlServer(_connection); - if (_rowNumberPaging) - { - optionBuilder.UseRowNumberForPaging(); - } - } + => optionsBuilder.UseSqlServer( + _connection, b => + { + if (_rowNumberPaging) + { + b.UseRowNumberForPaging(); + } + }); } // ReSharper disable once ClassNeverInstantiated.Local diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/ComplexNavigationsQuerySqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/ComplexNavigationsQuerySqlServerFixture.cs index 16726e7e8e9..a63be628cf7 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/ComplexNavigationsQuerySqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/ComplexNavigationsQuerySqlServerFixture.cs @@ -34,10 +34,11 @@ public override SqlServerTestStore CreateTestStore() { return SqlServerTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(_connectionString); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(_connectionString) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new ComplexNavigationsContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new ComplexNavigationsContext(optionsBuilder.Options)) { // TODO: Delete DB if model changed context.Database.EnsureDeleted(); @@ -54,10 +55,11 @@ public override SqlServerTestStore CreateTestStore() public override ComplexNavigationsContext CreateContext(SqlServerTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(testStore.Connection); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(testStore.Connection) + .UseInternalServiceProvider(_serviceProvider); - var context = new ComplexNavigationsContext(_serviceProvider, optionsBuilder.Options); + var context = new ComplexNavigationsContext(optionsBuilder.Options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/CompositeKeyEndToEndTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/CompositeKeyEndToEndTest.cs index 0445093747a..9a42e30b185 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/CompositeKeyEndToEndTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/CompositeKeyEndToEndTest.cs @@ -179,11 +179,12 @@ public async Task Only_one_part_of_a_composite_key_needs_to_vary_for_uniquness() private class BronieContext : DbContext { + private readonly IServiceProvider _serviceProvider; private readonly string _databaseName; public BronieContext(IServiceProvider serviceProvider, string databaseName) - : base(serviceProvider) { + _serviceProvider = serviceProvider; _databaseName = databaseName; } @@ -192,9 +193,9 @@ public BronieContext(IServiceProvider serviceProvider, string databaseName) public DbSet EarthPonies { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)); - } + => optionsBuilder + .UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/ComputedColumnTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/ComputedColumnTest.cs index a960f10574e..bad1fd9affc 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/ComputedColumnTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/ComputedColumnTest.cs @@ -57,20 +57,21 @@ public void Can_use_computed_columns_with_null_values() private class Context : DbContext { + private readonly IServiceProvider _serviceProvider; private readonly string _databaseName; public Context(IServiceProvider serviceProvider, string databaseName) - : base(serviceProvider) { + _serviceProvider = serviceProvider; _databaseName = databaseName; } public DbSet Entities { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)); - } + => optionsBuilder + .UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -112,27 +113,27 @@ public class EnumItem private class NullableContext : DbContext { + private readonly IServiceProvider _serviceProvider; private readonly string _databaseName; public NullableContext(IServiceProvider serviceProvider, string databaseName) - : base(serviceProvider) + : base() { + _serviceProvider = serviceProvider; _databaseName = databaseName; } public DbSet EnumItems { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)); - } + => optionsBuilder + .UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity() + => modelBuilder.Entity() .Property(entity => entity.CalculatedFlagEnum) .ForSqlServerHasComputedColumnSql("FlagEnum | OptionalFlagEnum"); - } } [Fact] diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/DataAnnotationSqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/DataAnnotationSqlServerFixture.cs index 2c79cbbeb4d..587eab0fcb2 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/DataAnnotationSqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/DataAnnotationSqlServerFixture.cs @@ -30,30 +30,33 @@ public DataAnnotationSqlServerFixture() public override SqlServerTestStore CreateTestStore() { return SqlServerTestStore.GetOrCreateShared(DatabaseName, () => - { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(_connectionString); - - using (var context = new DataAnnotationContext(_serviceProvider, optionsBuilder.Options)) { - // TODO: Delete DB if model changed - context.Database.EnsureDeleted(); - if (context.Database.EnsureCreated()) + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(_connectionString) + .UseInternalServiceProvider(_serviceProvider); + + using (var context = new DataAnnotationContext(optionsBuilder.Options)) { - DataAnnotationModelInitializer.Seed(context); - } + // TODO: Delete DB if model changed + context.Database.EnsureDeleted(); + if (context.Database.EnsureCreated()) + { + DataAnnotationModelInitializer.Seed(context); + } - TestSqlLoggerFactory.SqlStatements.Clear(); - } - }); + TestSqlLoggerFactory.SqlStatements.Clear(); + } + }); } public override DataAnnotationContext CreateContext(SqlServerTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.EnableSensitiveDataLogging().UseSqlServer(testStore.Connection); + var optionsBuilder = new DbContextOptionsBuilder() + .EnableSensitiveDataLogging() + .UseSqlServer(testStore.Connection) + .UseInternalServiceProvider(_serviceProvider); - var context = new DataAnnotationContext(_serviceProvider, optionsBuilder.Options); + var context = new DataAnnotationContext(optionsBuilder.Options); context.Database.UseTransaction(testStore.Transaction); return context; } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/DefaultValuesTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/DefaultValuesTest.cs index 904eee668a0..14876a81d1f 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/DefaultValuesTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/DefaultValuesTest.cs @@ -51,28 +51,27 @@ public void Dispose() private class ChipsContext : DbContext { + private readonly IServiceProvider _serviceProvider; private readonly string _databaseName; public ChipsContext(IServiceProvider serviceProvider, string databaseName) - : base(serviceProvider) { + _serviceProvider = serviceProvider; _databaseName = databaseName; } public DbSet Chips { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)); - } + => optionsBuilder + .UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity() + => modelBuilder.Entity() .Property(e => e.BestBuyDate) .ValueGeneratedOnAdd() .HasDefaultValue(new DateTime(2035, 9, 25)); - } } private class KettleChips diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/ExistingConnectionTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/ExistingConnectionTest.cs index b1efa2f1a0f..fb68e8c5fe0 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/ExistingConnectionTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/ExistingConnectionTest.cs @@ -88,29 +88,28 @@ private static async Task Can_use_an_existing_closed_connection_test(bool openCo private class NorthwindContext : DbContext { + private readonly IServiceProvider _serviceProvider; private readonly SqlConnection _connection; public NorthwindContext(IServiceProvider serviceProvider, SqlConnection connection) - : base(serviceProvider) { + _serviceProvider = serviceProvider; _connection = connection; } public DbSet Customers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(_connection); - } + => optionsBuilder + .UseSqlServer(_connection) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity(b => + => modelBuilder.Entity(b => { b.HasKey(c => c.CustomerID); b.ForSqlServerToTable("Customers"); }); - } } private class Customer diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/F1SqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/F1SqlServerFixture.cs index 9981f476a8f..bbc167f39ae 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/F1SqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/F1SqlServerFixture.cs @@ -32,10 +32,11 @@ public override SqlServerTestStore CreateTestStore() { return SqlServerTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(_connectionString); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(_connectionString) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new F1Context(_serviceProvider, optionsBuilder.Options)) + using (var context = new F1Context(optionsBuilder.Options)) { // TODO: Delete DB if model changed context.Database.EnsureDeleted(); @@ -51,10 +52,11 @@ public override SqlServerTestStore CreateTestStore() public override F1Context CreateContext(SqlServerTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(testStore.Connection); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(testStore.Connection) + .UseInternalServiceProvider(_serviceProvider); - var context = new F1Context(_serviceProvider, optionsBuilder.Options); + var context = new F1Context(optionsBuilder.Options); context.Database.UseTransaction(testStore.Transaction); return context; } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/GearsOfWarQuerySqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/GearsOfWarQuerySqlServerFixture.cs index cb2b60368d8..85267d64e87 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/GearsOfWarQuerySqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/GearsOfWarQuerySqlServerFixture.cs @@ -33,10 +33,11 @@ public override SqlServerTestStore CreateTestStore() { return SqlServerTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(_connectionString); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(_connectionString) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new GearsOfWarContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new GearsOfWarContext(optionsBuilder.Options)) { // TODO: Delete DB if model changed context.Database.EnsureDeleted(); @@ -56,9 +57,10 @@ public override GearsOfWarContext CreateContext(SqlServerTestStore testStore) optionsBuilder .EnableSensitiveDataLogging() + .UseInternalServiceProvider(_serviceProvider) .UseSqlServer(testStore.Connection); - var context = new GearsOfWarContext(_serviceProvider, optionsBuilder.Options); + var context = new GearsOfWarContext(optionsBuilder.Options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/GraphUpdatesSqlServerTestBase.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/GraphUpdatesSqlServerTestBase.cs index f47065d9dd5..06387e65640 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/GraphUpdatesSqlServerTestBase.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/GraphUpdatesSqlServerTestBase.cs @@ -35,10 +35,11 @@ public override SqlServerTestStore CreateTestStore() { return SqlServerTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString(DatabaseName)); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(SqlServerTestStore.CreateConnectionString(DatabaseName)) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new GraphUpdatesContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new GraphUpdatesContext(optionsBuilder.Options)) { context.Database.EnsureDeleted(); if (context.Database.EnsureCreated()) @@ -51,10 +52,11 @@ public override SqlServerTestStore CreateTestStore() public override DbContext CreateContext(SqlServerTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(testStore.Connection); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(testStore.Connection) + .UseInternalServiceProvider(_serviceProvider); - var context = new GraphUpdatesContext(_serviceProvider, optionsBuilder.Options); + var context = new GraphUpdatesContext(optionsBuilder.Options); context.Database.UseTransaction(testStore.Transaction); return context; } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/InheritanceRelationshipsQuerySqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/InheritanceRelationshipsQuerySqlServerFixture.cs index 4152936eff0..ac2dcd4f49a 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/InheritanceRelationshipsQuerySqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/InheritanceRelationshipsQuerySqlServerFixture.cs @@ -33,10 +33,11 @@ public override SqlServerTestStore CreateTestStore() { return SqlServerTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(_connectionString); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(_connectionString) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new InheritanceRelationshipsContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new InheritanceRelationshipsContext(optionsBuilder.Options)) { // TODO: Delete DB if model changed context.Database.EnsureDeleted(); @@ -52,10 +53,11 @@ public override SqlServerTestStore CreateTestStore() public override InheritanceRelationshipsContext CreateContext(SqlServerTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(testStore.Connection); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(testStore.Connection) + .UseInternalServiceProvider(_serviceProvider); - var context = new InheritanceRelationshipsContext(_serviceProvider, optionsBuilder.Options); + var context = new InheritanceRelationshipsContext(optionsBuilder.Options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/InheritanceSqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/InheritanceSqlServerFixture.cs index 090c1b6bc29..01d777c582a 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/InheritanceSqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/InheritanceSqlServerFixture.cs @@ -14,28 +14,25 @@ namespace Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests public class InheritanceSqlServerFixture : InheritanceRelationalFixture, IDisposable { private readonly DbContextOptions _options; - private readonly IServiceProvider _serviceProvider; private readonly SqlServerTestStore _testStore; public InheritanceSqlServerFixture() { - _serviceProvider - = new ServiceCollection() - .AddEntityFramework() - .AddSqlServer() - .AddSingleton(TestSqlServerModelSource.GetFactory(OnModelCreating)) - .AddSingleton(new TestSqlLoggerFactory()) - .BuildServiceProvider(); + var serviceProvider = new ServiceCollection() + .AddEntityFramework() + .AddSqlServer() + .AddSingleton(TestSqlServerModelSource.GetFactory(OnModelCreating)) + .AddSingleton(new TestSqlLoggerFactory()) + .BuildServiceProvider(); _testStore = SqlServerTestStore.CreateScratch(); - var optionsBuilder = new DbContextOptionsBuilder(); - - optionsBuilder + _options = new DbContextOptionsBuilder() .EnableSensitiveDataLogging() - .UseSqlServer(_testStore.Connection); + .UseSqlServer(_testStore.Connection) + .UseInternalServiceProvider(serviceProvider) + .Options; - _options = optionsBuilder.Options; using (var context = CreateContext()) { context.Database.EnsureCreated(); @@ -43,7 +40,7 @@ public InheritanceSqlServerFixture() } } - public override InheritanceContext CreateContext() => new InheritanceContext(_serviceProvider, _options); + public override InheritanceContext CreateContext() => new InheritanceContext(_options); public void Dispose() => _testStore.Dispose(); } } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/MappingQuerySqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/MappingQuerySqlServerFixture.cs index 176009f7d90..9404ffc1f36 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/MappingQuerySqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/MappingQuerySqlServerFixture.cs @@ -27,14 +27,16 @@ public MappingQuerySqlServerFixture() _testDatabase = SqlServerNorthwindContext.GetSharedStore(); - var optionsBuilder = new DbContextOptionsBuilder().UseModel(CreateModel()); - optionsBuilder.UseSqlServer(_testDatabase.ConnectionString); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseModel(CreateModel()) + .UseSqlServer(_testDatabase.ConnectionString) + .UseInternalServiceProvider(_serviceProvider) + .Options; } public DbContext CreateContext() { - var context = new DbContext(_serviceProvider, _options); + var context = new DbContext(_options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/MigrationsSqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/MigrationsSqlServerFixture.cs index 7df9f38bbea..fce0ce490fc 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/MigrationsSqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/MigrationsSqlServerFixture.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Data.SqlClient; using Microsoft.EntityFrameworkCore.FunctionalTests; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -13,11 +12,10 @@ namespace Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests public class MigrationsSqlServerFixture : MigrationsFixtureBase { private readonly DbContextOptions _options; - private readonly IServiceProvider _serviceProvider; public MigrationsSqlServerFixture() { - _serviceProvider = new ServiceCollection() + var serviceProvider = new ServiceCollection() .AddEntityFramework() .AddSqlServer() .BuildServiceProvider(); @@ -27,11 +25,11 @@ public MigrationsSqlServerFixture() InitialCatalog = nameof(MigrationsSqlServerTest) }; - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(connectionStringBuilder.ConnectionString); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseInternalServiceProvider(serviceProvider) + .UseSqlServer(connectionStringBuilder.ConnectionString).Options; } - public override MigrationsContext CreateContext() => new MigrationsContext(_serviceProvider, _options); + public override MigrationsContext CreateContext() => new MigrationsContext(_options); } } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NavigationTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NavigationTest.cs index 52a48254d81..07d78cca832 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NavigationTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NavigationTest.cs @@ -76,8 +76,8 @@ public class Person public class GoTContext : DbContext { - public GoTContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public GoTContext(DbContextOptions options) + : base(options) { } @@ -109,11 +109,12 @@ public NavigationTestFixture() ["Trusted_Connection"] = true }; - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(connStrBuilder.ConnectionString); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseSqlServer(connStrBuilder.ConnectionString) + .UseInternalServiceProvider(_serviceProvider) + .Options; } - public virtual GoTContext CreateContext() => new GoTContext(_serviceProvider, _options); + public virtual GoTContext CreateContext() => new GoTContext(_options); } } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NorthwindQuerySqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NorthwindQuerySqlServerFixture.cs index 9e86d4a276e..52f314a467c 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NorthwindQuerySqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NorthwindQuerySqlServerFixture.cs @@ -35,27 +35,23 @@ public NorthwindQuerySqlServerFixture() } protected DbContextOptions BuildOptions() - { - var optionsBuilder = new DbContextOptionsBuilder(); - - var sqlServerDbContextOptionsBuilder - = optionsBuilder - .EnableSensitiveDataLogging() - .UseSqlServer(_testStore.ConnectionString); - - ConfigureOptions(sqlServerDbContextOptionsBuilder); - - sqlServerDbContextOptionsBuilder.ApplyConfiguration(); - - return optionsBuilder.Options; - } + => new DbContextOptionsBuilder() + .EnableSensitiveDataLogging() + .UseInternalServiceProvider(_serviceProvider) + .UseSqlServer( + _testStore.ConnectionString, + b => + { + ConfigureOptions(b); + b.ApplyConfiguration(); + }).Options; protected virtual void ConfigureOptions(SqlServerDbContextOptionsBuilder sqlServerDbContextOptionsBuilder) { } public override NorthwindContext CreateContext() - => new SqlServerNorthwindContext(_serviceProvider, _options); + => new SqlServerNorthwindContext(_options); public void Dispose() => _testStore.Dispose(); diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NorthwindSprocQuerySqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NorthwindSprocQuerySqlServerFixture.cs index 994b3466641..e330bd6356d 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NorthwindSprocQuerySqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NorthwindSprocQuerySqlServerFixture.cs @@ -15,7 +15,6 @@ namespace Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests { public class NorthwindSprocQuerySqlServerFixture : NorthwindSprocQueryRelationalFixture, IDisposable { - private readonly IServiceProvider _serviceProvider; private readonly DbContextOptions _options; private readonly SqlServerTestStore _testStore; @@ -23,27 +22,24 @@ public NorthwindSprocQuerySqlServerFixture() { _testStore = SqlServerNorthwindContext.GetSharedStore(); - _serviceProvider = new ServiceCollection() + var serviceProvider = new ServiceCollection() .AddEntityFramework() .AddSqlServer() .AddSingleton(TestSqlServerModelSource.GetFactory(OnModelCreating)) .AddSingleton(new TestSqlLoggerFactory()) .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - - optionsBuilder + _options = new DbContextOptionsBuilder() .EnableSensitiveDataLogging() - .UseSqlServer(_testStore.ConnectionString); - - _options = optionsBuilder.Options; + .UseInternalServiceProvider(serviceProvider) + .UseSqlServer(_testStore.ConnectionString).Options; - _serviceProvider.GetRequiredService(); + serviceProvider.GetRequiredService(); } public override NorthwindContext CreateContext() { - var context = new SqlServerNorthwindContext(_serviceProvider, _options); + var context = new SqlServerNorthwindContext(_options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NotificationEntitiesSqlServerTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NotificationEntitiesSqlServerTest.cs index ae0f77843cb..3a2b065c7b9 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NotificationEntitiesSqlServerTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NotificationEntitiesSqlServerTest.cs @@ -19,26 +19,24 @@ public NotificationEntitiesSqlServerTest(NotificationEntitiesSqlServerFixture fi public class NotificationEntitiesSqlServerFixture : NotificationEntitiesFixtureBase { - private readonly IServiceProvider _serviceProvider; private readonly DbContextOptions _options; public NotificationEntitiesSqlServerFixture() { - _serviceProvider = new ServiceCollection() - .AddEntityFramework() - .AddSqlServer() - .AddSingleton(TestSqlServerModelSource.GetFactory(OnModelCreating)) - .BuildServiceProvider(); - - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString("NotificationEntities")); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseSqlServer(SqlServerTestStore.CreateConnectionString("NotificationEntities")) + .UseInternalServiceProvider(new ServiceCollection() + .AddEntityFramework() + .AddSqlServer() + .AddSingleton(TestSqlServerModelSource.GetFactory(OnModelCreating)) + .BuildServiceProvider()) + .Options; EnsureCreated(); } public override DbContext CreateContext() - => new DbContext(_serviceProvider, _options); + => new DbContext(_options); } } } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NullKeysSqlServerTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NullKeysSqlServerTest.cs index abf026d2e15..d983f3bb19c 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NullKeysSqlServerTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NullKeysSqlServerTest.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.EntityFrameworkCore.FunctionalTests; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests.Utilities; @@ -18,28 +17,24 @@ public NullKeysSqlServerTest(NullKeysSqlServerFixture fixture) public class NullKeysSqlServerFixture : NullKeysFixtureBase { - private readonly IServiceProvider _serviceProvider; private readonly DbContextOptions _options; public NullKeysSqlServerFixture() { - _serviceProvider = new ServiceCollection() - .AddEntityFramework() - .AddSqlServer() - .AddSingleton(TestSqlServerModelSource.GetFactory(OnModelCreating)) - .BuildServiceProvider(); - - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString("StringsContext")); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseSqlServer(SqlServerTestStore.CreateConnectionString("StringsContext")) + .UseInternalServiceProvider(new ServiceCollection() + .AddEntityFramework() + .AddSqlServer() + .AddSingleton(TestSqlServerModelSource.GetFactory(OnModelCreating)) + .BuildServiceProvider()) + .Options; EnsureCreated(); } public override DbContext CreateContext() - { - return new DbContext(_serviceProvider, _options); - } + => new DbContext(_options); } } } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NullSemanticsQuerySqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NullSemanticsQuerySqlServerFixture.cs index ac8eba77b82..327a7fc0e4d 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NullSemanticsQuerySqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/NullSemanticsQuerySqlServerFixture.cs @@ -33,10 +33,9 @@ public override SqlServerTestStore CreateTestStore() { return SqlServerTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(_connectionString); - - using (var context = new NullSemanticsContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new NullSemanticsContext(new DbContextOptionsBuilder() + .UseSqlServer(_connectionString) + .UseInternalServiceProvider(_serviceProvider).Options)) { // TODO: Delete DB if model changed @@ -52,19 +51,18 @@ public override SqlServerTestStore CreateTestStore() public override NullSemanticsContext CreateContext(SqlServerTestStore testStore, bool useRelationalNulls) { - var optionsBuilder = new DbContextOptionsBuilder(); - - var sqlServerOptions - = optionsBuilder - .EnableSensitiveDataLogging() - .UseSqlServer(testStore.Connection); - - if (useRelationalNulls) - { - sqlServerOptions.UseRelationalNulls(); - } - - var context = new NullSemanticsContext(_serviceProvider, optionsBuilder.Options); + var context = new NullSemanticsContext(new DbContextOptionsBuilder() + .EnableSensitiveDataLogging() + .UseInternalServiceProvider(_serviceProvider) + .UseSqlServer( + testStore.Connection, + b => + { + if (useRelationalNulls) + { + b.UseRelationalNulls(); + } + }).Options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/OneToOneQuerySqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/OneToOneQuerySqlServerFixture.cs index 30de3e47f3c..c7f5fdab6d5 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/OneToOneQuerySqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/OneToOneQuerySqlServerFixture.cs @@ -13,26 +13,23 @@ namespace Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests public class OneToOneQuerySqlServerFixture : OneToOneQueryFixtureBase, IDisposable { private readonly DbContextOptions _options; - private readonly IServiceProvider _serviceProvider; private readonly SqlServerTestStore _testStore; public OneToOneQuerySqlServerFixture() { - _serviceProvider - = new ServiceCollection() + _testStore = SqlServerTestStore.CreateScratch(); + + _options = new DbContextOptionsBuilder() + .UseSqlServer(_testStore.ConnectionString) + .UseInternalServiceProvider(new ServiceCollection() .AddEntityFramework() .AddSqlServer() .AddSingleton(TestSqlServerModelSource.GetFactory(OnModelCreating)) .AddSingleton(new TestSqlLoggerFactory()) - .BuildServiceProvider(); - - _testStore = SqlServerTestStore.CreateScratch(); - - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(_testStore.ConnectionString); - _options = optionsBuilder.Options; + .BuildServiceProvider()) + .Options; - using (var context = new DbContext(_serviceProvider, _options)) + using (var context = new DbContext(_options)) { context.Database.EnsureCreated(); @@ -40,7 +37,8 @@ public OneToOneQuerySqlServerFixture() } } - public DbContext CreateContext() => new DbContext(_serviceProvider, _options); + public DbContext CreateContext() => new DbContext(_options); + public void Dispose() => _testStore.Dispose(); } } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/QueryBugsTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/QueryBugsTest.cs index 5e0c987d936..c0602a3fa97 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/QueryBugsTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/QueryBugsTest.cs @@ -113,15 +113,19 @@ private class Product private class MyContext603 : DbContext { - public MyContext603(IServiceProvider provider) - : base(provider) + private readonly IServiceProvider _serviceProvider; + + public MyContext603(IServiceProvider serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Products { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString("Repro603")); + => optionsBuilder + .UseSqlServer(SqlServerTestStore.CreateConnectionString("Repro603")) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().ToTable("Product"); @@ -237,9 +241,11 @@ public class Order public class MyContext925 : DbContext { + private readonly IServiceProvider _serviceProvider; + public MyContext925(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Customers { get; set; } @@ -248,7 +254,8 @@ public MyContext925(IServiceProvider serviceProvider) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .EnableSensitiveDataLogging() - .UseSqlServer(SqlServerTestStore.CreateConnectionString("Repro925")); + .UseSqlServer(SqlServerTestStore.CreateConnectionString("Repro925")) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -377,9 +384,11 @@ public class Details // TODO: replace with GearsOfWar context when it's refactored properly public class MyContext963 : DbContext { - public MyContext963(IServiceProvider provider) - : base(provider) + private readonly IServiceProvider _serviceProvider; + + public MyContext963(IServiceProvider serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Targaryens { get; set; } @@ -388,7 +397,9 @@ public MyContext963(IServiceProvider provider) public DbSet Dragons { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString("Repro963")); + => optionsBuilder + .UseSqlServer(SqlServerTestStore.CreateConnectionString("Repro963")) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -497,16 +508,20 @@ public void Customer_collections_materialize_properly_3758() public class MyContext3758 : DbContext { - public MyContext3758(IServiceProvider provider) - : base(provider) + private readonly IServiceProvider _serviceProvider; + + public MyContext3758(IServiceProvider serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Customers { get; set; } public DbSet Orders { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString("Repro3758")); + => optionsBuilder + .UseSqlServer(SqlServerTestStore.CreateConnectionString("Repro3758")) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SequenceEndToEndTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SequenceEndToEndTest.cs index fe24ddd0125..b13572469cb 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SequenceEndToEndTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SequenceEndToEndTest.cs @@ -220,20 +220,21 @@ private static void AddEntitiesWithIds(IServiceProvider serviceProvider, int idO private class BronieContext : DbContext { + private readonly IServiceProvider _serviceProvider; private readonly string _databaseName; public BronieContext(IServiceProvider serviceProvider, string databaseName) - : base(serviceProvider) { + _serviceProvider = serviceProvider; _databaseName = databaseName; } public DbSet Pegasuses { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)); - } + => optionsBuilder + .UseInternalServiceProvider(_serviceProvider) + .UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -327,12 +328,13 @@ private static void AddEntitiesNullable(IServiceProvider serviceProvider, string private class NullableBronieContext : DbContext { + private readonly IServiceProvider _serviceProvider; private readonly string _databaseName; private readonly bool _useSequence; public NullableBronieContext(IServiceProvider serviceProvider, string databaseName, bool useSequence) - : base(serviceProvider) { + _serviceProvider = serviceProvider; _databaseName = databaseName; _useSequence = useSequence; } @@ -340,9 +342,9 @@ public NullableBronieContext(IServiceProvider serviceProvider, string databaseNa public DbSet Unicons { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)); - } + => optionsBuilder + .UseInternalServiceProvider(_serviceProvider) + .UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)); protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SequentialGuidEndToEndTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SequentialGuidEndToEndTest.cs index 75cae8c6f7c..3eac5452d24 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SequentialGuidEndToEndTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SequentialGuidEndToEndTest.cs @@ -83,20 +83,21 @@ public async Task Can_use_explicit_values() private class BronieContext : DbContext { + private readonly IServiceProvider _serviceProvider; private readonly string _databaseName; public BronieContext(IServiceProvider serviceProvider, string databaseName) - : base(serviceProvider) { + _serviceProvider = serviceProvider; _databaseName = databaseName; } public DbSet Pegasuses { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)); - } + => optionsBuilder + .UseSqlServer(SqlServerTestStore.CreateConnectionString(_databaseName)) + .UseInternalServiceProvider(_serviceProvider); } private class Pegasus diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlAzure/BatchingSqlAzureFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlAzure/BatchingSqlAzureFixture.cs index 74353451aab..d8b556d2382 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlAzure/BatchingSqlAzureFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlAzure/BatchingSqlAzureFixture.cs @@ -10,9 +10,11 @@ public class BatchingSqlAzureFixture : SqlAzureFixture { public AdventureWorksContext CreateContext(int maxBatchSize) { - var optionsBuilder = new DbContextOptionsBuilder(Options); + var optionsBuilder = new DbContextOptionsBuilder(Options).UseInternalServiceProvider(Services); + new SqlServerDbContextOptionsBuilder(optionsBuilder).MaxBatchSize(maxBatchSize); - return new AdventureWorksContext(Services, optionsBuilder.Options); + + return new AdventureWorksContext(optionsBuilder.Options); } } } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlAzure/Model/AdventureWorksContext.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlAzure/Model/AdventureWorksContext.cs index 6cc81ead68a..90c145dd701 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlAzure/Model/AdventureWorksContext.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlAzure/Model/AdventureWorksContext.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.EntityFrameworkCore.Infrastructure; namespace Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests.SqlAzure.Model @@ -9,257 +8,254 @@ namespace Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests.SqlAzure.Model public class AdventureWorksContext : DbContext { public AdventureWorksContext(DbContextOptions options) - : base(options) - { } - - public AdventureWorksContext(IServiceProvider services, DbContextOptions options) - : base(services, options) - { } + : base(options) + { + } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity
(entity => - { - entity.HasIndex(e => new { e.AddressLine1, e.AddressLine2, e.City, e.StateProvince, e.PostalCode, e.CountryRegion }) - .HasName("IX_Address_AddressLine1_AddressLine2_City_StateProvince_PostalCode_CountryRegion"); + { + entity.HasIndex(e => new { e.AddressLine1, e.AddressLine2, e.City, e.StateProvince, e.PostalCode, e.CountryRegion }) + .HasName("IX_Address_AddressLine1_AddressLine2_City_StateProvince_PostalCode_CountryRegion"); - entity.HasIndex(e => e.StateProvince) - .HasName("IX_Address_StateProvince"); + entity.HasIndex(e => e.StateProvince) + .HasName("IX_Address_StateProvince"); - entity.HasIndex(e => e.rowguid) - .HasName("AK_Address_rowguid") - .IsUnique(); + entity.HasIndex(e => e.rowguid) + .HasName("AK_Address_rowguid") + .IsUnique(); - entity.Property(e => e.ModifiedDate) - .HasColumnType("datetime") - .HasDefaultValueSql("getdate()"); + entity.Property(e => e.ModifiedDate) + .HasColumnType("datetime") + .HasDefaultValueSql("getdate()"); - entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); - }); + entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); + }); modelBuilder.Entity(entity => - { - entity.HasIndex(e => e.EmailAddress) - .HasName("IX_Customer_EmailAddress"); + { + entity.HasIndex(e => e.EmailAddress) + .HasName("IX_Customer_EmailAddress"); - entity.HasIndex(e => e.rowguid) - .HasName("AK_Customer_rowguid") - .IsUnique(); + entity.HasIndex(e => e.rowguid) + .HasName("AK_Customer_rowguid") + .IsUnique(); - entity.Property(e => e.ModifiedDate) - .HasColumnType("datetime") - .HasDefaultValueSql("getdate()"); + entity.Property(e => e.ModifiedDate) + .HasColumnType("datetime") + .HasDefaultValueSql("getdate()"); - entity.Property(e => e.PasswordHash).HasColumnType("varchar(128)"); + entity.Property(e => e.PasswordHash).HasColumnType("varchar(128)"); - entity.Property(e => e.PasswordSalt).HasColumnType("varchar(10)"); + entity.Property(e => e.PasswordSalt).HasColumnType("varchar(10)"); - entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); - }); + entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); + }); modelBuilder.Entity(entity => - { - entity.HasKey(e => new { e.CustomerID, e.AddressID }) - .HasName("PK_CustomerAddress_CustomerID_AddressID"); + { + entity.HasKey(e => new { e.CustomerID, e.AddressID }) + .HasName("PK_CustomerAddress_CustomerID_AddressID"); - entity.HasIndex(e => e.rowguid) - .HasName("AK_CustomerAddress_rowguid") - .IsUnique(); + entity.HasIndex(e => e.rowguid) + .HasName("AK_CustomerAddress_rowguid") + .IsUnique(); - entity.Property(e => e.ModifiedDate) - .HasColumnType("datetime") - .HasDefaultValueSql("getdate()"); + entity.Property(e => e.ModifiedDate) + .HasColumnType("datetime") + .HasDefaultValueSql("getdate()"); - entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); - }); + entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); + }); modelBuilder.Entity(entity => - { - entity.HasIndex(e => e.ProductNumber) - .HasName("AK_Product_ProductNumber") - .IsUnique(); + { + entity.HasIndex(e => e.ProductNumber) + .HasName("AK_Product_ProductNumber") + .IsUnique(); - entity.HasIndex(e => e.rowguid) - .HasName("AK_Product_rowguid") - .IsUnique(); + entity.HasIndex(e => e.rowguid) + .HasName("AK_Product_rowguid") + .IsUnique(); - entity.HasIndex(e => e.Name) - .HasName("AK_Product_Name") - .IsUnique(); + entity.HasIndex(e => e.Name) + .HasName("AK_Product_Name") + .IsUnique(); - entity.Property(e => e.DiscontinuedDate).HasColumnType("datetime"); + entity.Property(e => e.DiscontinuedDate).HasColumnType("datetime"); - entity.Property(e => e.ListPrice).HasColumnType("money"); + entity.Property(e => e.ListPrice).HasColumnType("money"); - entity.Property(e => e.ModifiedDate) - .HasColumnType("datetime") - .HasDefaultValueSql("getdate()"); + entity.Property(e => e.ModifiedDate) + .HasColumnType("datetime") + .HasDefaultValueSql("getdate()"); - entity.Property(e => e.SellEndDate).HasColumnType("datetime"); + entity.Property(e => e.SellEndDate).HasColumnType("datetime"); - entity.Property(e => e.SellStartDate).HasColumnType("datetime"); + entity.Property(e => e.SellStartDate).HasColumnType("datetime"); - entity.Property(e => e.StandardCost).HasColumnType("money"); + entity.Property(e => e.StandardCost).HasColumnType("money"); - entity.Property(e => e.ThumbNailPhoto).HasColumnType("varbinary(max)"); + entity.Property(e => e.ThumbNailPhoto).HasColumnType("varbinary(max)"); - entity.Property(e => e.Weight).HasColumnType("decimal"); + entity.Property(e => e.Weight).HasColumnType("decimal"); - entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); - }); + entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); + }); modelBuilder.Entity(entity => - { - entity.HasIndex(e => e.Name) - .HasName("AK_ProductCategory_Name") - .IsUnique(); + { + entity.HasIndex(e => e.Name) + .HasName("AK_ProductCategory_Name") + .IsUnique(); - entity.HasIndex(e => e.rowguid) - .HasName("AK_ProductCategory_rowguid") - .IsUnique(); + entity.HasIndex(e => e.rowguid) + .HasName("AK_ProductCategory_rowguid") + .IsUnique(); - entity.Property(e => e.ModifiedDate) - .HasColumnType("datetime") - .HasDefaultValueSql("getdate()"); + entity.Property(e => e.ModifiedDate) + .HasColumnType("datetime") + .HasDefaultValueSql("getdate()"); - entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); - }); + entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); + }); modelBuilder.Entity(entity => - { - entity.HasIndex(e => e.rowguid) - .HasName("AK_ProductDescription_rowguid") - .IsUnique(); + { + entity.HasIndex(e => e.rowguid) + .HasName("AK_ProductDescription_rowguid") + .IsUnique(); - entity.Property(e => e.ModifiedDate) - .HasColumnType("datetime") - .HasDefaultValueSql("getdate()"); + entity.Property(e => e.ModifiedDate) + .HasColumnType("datetime") + .HasDefaultValueSql("getdate()"); - entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); - }); + entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); + }); modelBuilder.Entity(entity => - { - entity.HasIndex(e => e.Name) - .HasName("AK_ProductModel_Name") - .IsUnique(); + { + entity.HasIndex(e => e.Name) + .HasName("AK_ProductModel_Name") + .IsUnique(); - entity.HasIndex(e => e.rowguid) - .HasName("AK_ProductModel_rowguid") - .IsUnique(); + entity.HasIndex(e => e.rowguid) + .HasName("AK_ProductModel_rowguid") + .IsUnique(); - entity.Property(e => e.ModifiedDate) - .HasColumnType("datetime") - .HasDefaultValueSql("getdate()"); + entity.Property(e => e.ModifiedDate) + .HasColumnType("datetime") + .HasDefaultValueSql("getdate()"); - entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); - }); + entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); + }); modelBuilder.Entity(entity => - { - entity.HasKey(e => new { e.ProductModelID, e.ProductDescriptionID, e.Culture }) - .HasName("PK_ProductModelProductDescription_ProductModelID_ProductDescriptionID_Culture"); + { + entity.HasKey(e => new { e.ProductModelID, e.ProductDescriptionID, e.Culture }) + .HasName("PK_ProductModelProductDescription_ProductModelID_ProductDescriptionID_Culture"); - entity.HasIndex(e => e.rowguid) - .HasName("AK_ProductModelProductDescription_rowguid") - .IsUnique(); + entity.HasIndex(e => e.rowguid) + .HasName("AK_ProductModelProductDescription_rowguid") + .IsUnique(); - entity.Property(e => e.Culture).HasColumnType("nchar(6)"); + entity.Property(e => e.Culture).HasColumnType("nchar(6)"); - entity.Property(e => e.ModifiedDate) - .HasColumnType("datetime") - .HasDefaultValueSql("getdate()"); + entity.Property(e => e.ModifiedDate) + .HasColumnType("datetime") + .HasDefaultValueSql("getdate()"); - entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); - }); + entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); + }); modelBuilder.Entity(entity => - { - entity.HasKey(e => new { e.SalesOrderID, e.SalesOrderDetailID }) - .HasName("PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID"); + { + entity.HasKey(e => new { e.SalesOrderID, e.SalesOrderDetailID }) + .HasName("PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID"); - entity.HasIndex(e => e.ProductID) - .HasName("IX_SalesOrderDetail_ProductID"); + entity.HasIndex(e => e.ProductID) + .HasName("IX_SalesOrderDetail_ProductID"); - entity.HasIndex(e => e.rowguid) - .HasName("AK_SalesOrderDetail_rowguid") - .IsUnique(); + entity.HasIndex(e => e.rowguid) + .HasName("AK_SalesOrderDetail_rowguid") + .IsUnique(); - entity.Property(e => e.SalesOrderDetailID).ValueGeneratedOnAdd(); + entity.Property(e => e.SalesOrderDetailID).ValueGeneratedOnAdd(); - entity.Property(e => e.LineTotal) - .HasColumnType("numeric") - .ValueGeneratedOnAddOrUpdate(); + entity.Property(e => e.LineTotal) + .HasColumnType("numeric") + .ValueGeneratedOnAddOrUpdate(); - entity.Property(e => e.ModifiedDate) - .HasColumnType("datetime") - .HasDefaultValueSql("getdate()"); + entity.Property(e => e.ModifiedDate) + .HasColumnType("datetime") + .HasDefaultValueSql("getdate()"); - entity.Property(e => e.UnitPrice).HasColumnType("money"); + entity.Property(e => e.UnitPrice).HasColumnType("money"); - entity.Property(e => e.UnitPriceDiscount) - .HasColumnType("money") - .HasDefaultValueSql("0.0"); + entity.Property(e => e.UnitPriceDiscount) + .HasColumnType("money") + .HasDefaultValueSql("0.0"); - entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); - }); + entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); + }); modelBuilder.Entity(entity => - { - entity.HasKey(e => e.SalesOrderID) - .HasName("PK_SalesOrderHeader_SalesOrderID"); + { + entity.HasKey(e => e.SalesOrderID) + .HasName("PK_SalesOrderHeader_SalesOrderID"); - entity.HasIndex(e => e.CustomerID) - .HasName("IX_SalesOrderHeader_CustomerID"); + entity.HasIndex(e => e.CustomerID) + .HasName("IX_SalesOrderHeader_CustomerID"); - entity.HasIndex(e => e.SalesOrderNumber) - .HasName("AK_SalesOrderHeader_SalesOrderNumber") - .IsUnique(); + entity.HasIndex(e => e.SalesOrderNumber) + .HasName("AK_SalesOrderHeader_SalesOrderNumber") + .IsUnique(); - entity.HasIndex(e => e.rowguid) - .HasName("AK_SalesOrderHeader_rowguid") - .IsUnique(); + entity.HasIndex(e => e.rowguid) + .HasName("AK_SalesOrderHeader_rowguid") + .IsUnique(); - entity.Property(e => e.SalesOrderID).ForSqlServerUseSequenceHiLo("SalesOrderNumber", "SalesLT"); + entity.Property(e => e.SalesOrderID).ForSqlServerUseSequenceHiLo("SalesOrderNumber", "SalesLT"); - entity.Property(e => e.CreditCardApprovalCode).HasColumnType("varchar(15)"); + entity.Property(e => e.CreditCardApprovalCode).HasColumnType("varchar(15)"); - entity.Property(e => e.DueDate).HasColumnType("datetime"); + entity.Property(e => e.DueDate).HasColumnType("datetime"); - entity.Property(e => e.Freight) - .HasColumnType("money") - .HasDefaultValueSql("0.00"); + entity.Property(e => e.Freight) + .HasColumnType("money") + .HasDefaultValueSql("0.00"); - entity.Property(e => e.ModifiedDate) - .HasColumnType("datetime") - .HasDefaultValueSql("getdate()"); + entity.Property(e => e.ModifiedDate) + .HasColumnType("datetime") + .HasDefaultValueSql("getdate()"); - entity.Property(e => e.OrderDate) - .HasColumnType("datetime") - .HasDefaultValueSql("getdate()"); + entity.Property(e => e.OrderDate) + .HasColumnType("datetime") + .HasDefaultValueSql("getdate()"); - entity.Property(e => e.RevisionNumber).HasDefaultValueSql("0"); + entity.Property(e => e.RevisionNumber).HasDefaultValueSql("0"); - entity.Property(e => e.SalesOrderNumber).ValueGeneratedOnAddOrUpdate(); + entity.Property(e => e.SalesOrderNumber).ValueGeneratedOnAddOrUpdate(); - entity.Property(e => e.ShipDate).HasColumnType("datetime"); + entity.Property(e => e.ShipDate).HasColumnType("datetime"); - entity.Property(e => e.Status).HasDefaultValueSql("1"); + entity.Property(e => e.Status).HasDefaultValueSql("1"); - entity.Property(e => e.SubTotal) - .HasColumnType("money") - .HasDefaultValueSql("0.00"); + entity.Property(e => e.SubTotal) + .HasColumnType("money") + .HasDefaultValueSql("0.00"); - entity.Property(e => e.TaxAmt) - .HasColumnType("money") - .HasDefaultValueSql("0.00"); + entity.Property(e => e.TaxAmt) + .HasColumnType("money") + .HasDefaultValueSql("0.00"); - entity.Property(e => e.TotalDue) - .HasColumnType("money") - .ValueGeneratedOnAddOrUpdate(); + entity.Property(e => e.TotalDue) + .HasColumnType("money") + .ValueGeneratedOnAddOrUpdate(); - entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); - }); + entity.Property(e => e.rowguid).HasDefaultValueSql("newid()"); + }); modelBuilder.HasSequence("SalesOrderNumber", "SalesLT"); } @@ -275,4 +271,4 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public virtual DbSet SalesOrderDetails { get; set; } public virtual DbSet SalesOrders { get; set; } } -} \ No newline at end of file +} diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlAzure/SqlAzureFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlAzure/SqlAzureFixture.cs index 7850cab3da2..613f75fcea2 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlAzure/SqlAzureFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlAzure/SqlAzureFixture.cs @@ -18,20 +18,19 @@ public class SqlAzureFixture public SqlAzureFixture() { - SqlServerTestStore.CreateDatabase("adventureworks", scriptPath: "SqlAzure/adventureworks.sql", recreateIfAlreadyExists: false); + SqlServerTestStore.CreateDatabase("adventureworks", scriptPath: "SqlAzure/adventureworks.sql"); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.EnableSensitiveDataLogging() - .UseSqlServer(SqlServerTestStore.CreateConnectionString("adventureworks")); - Options = optionsBuilder.Options; + Services = new ServiceCollection() + .AddEntityFramework() + .AddSqlServer() + .AddSingleton(new TestSqlLoggerFactory()).BuildServiceProvider(); - var serviceCollection = new ServiceCollection(); - serviceCollection.AddEntityFramework() - .AddSqlServer(); - serviceCollection.AddSingleton(new TestSqlLoggerFactory()); - Services = serviceCollection.BuildServiceProvider(); + Options = new DbContextOptionsBuilder() + .UseInternalServiceProvider(Services) + .EnableSensitiveDataLogging() + .UseSqlServer(SqlServerTestStore.CreateConnectionString("adventureworks")).Options; } - public virtual AdventureWorksContext CreateContext() => new AdventureWorksContext(Services, Options); + public virtual AdventureWorksContext CreateContext() => new AdventureWorksContext(Options); } } \ No newline at end of file diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs index 9bb5bce791a..7abd272e15d 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerConfigPatternsTest.cs @@ -33,14 +33,10 @@ private class NorthwindContext : DbContext public DbSet Customers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); - } + => optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); } } @@ -51,10 +47,9 @@ public async Task Can_query_with_implicit_services_and_explicit_config() { using (SqlServerNorthwindContext.GetSharedStore()) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); - - using (var context = new NorthwindContext(optionsBuilder.Options)) + using (var context = new NorthwindContext( + new DbContextOptionsBuilder() + .UseSqlServer(SqlServerNorthwindContext.ConnectionString).Options)) { Assert.Equal(91, await context.Customers.CountAsync()); } @@ -71,9 +66,7 @@ public NorthwindContext(DbContextOptions options) public DbSet Customers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); } } @@ -84,14 +77,12 @@ public async Task Can_query_with_explicit_services_and_OnConfiguring() { using (SqlServerNorthwindContext.GetSharedStore()) { - var serviceCollection = new ServiceCollection(); - serviceCollection - .AddEntityFramework() - .AddSqlServer(); - - var serviceProvider = serviceCollection.BuildServiceProvider(); - - using (var context = new NorthwindContext(serviceProvider)) + using (var context = new NorthwindContext( + new DbContextOptionsBuilder().UseInternalServiceProvider( + new ServiceCollection() + .AddEntityFramework() + .AddSqlServer() + .BuildServiceProvider()).Options)) { Assert.Equal(91, await context.Customers.CountAsync()); } @@ -100,22 +91,19 @@ public async Task Can_query_with_explicit_services_and_OnConfiguring() private class NorthwindContext : DbContext { - public NorthwindContext(IServiceProvider serviceProvider) - : base(serviceProvider) + public NorthwindContext(DbContextOptions options) + : base(options) { } public DbSet Customers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); - } + => optionsBuilder + .UseSqlServer(SqlServerNorthwindContext.ConnectionString); protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); } } @@ -126,17 +114,12 @@ public async Task Can_query_with_explicit_services_and_explicit_config() { using (SqlServerNorthwindContext.GetSharedStore()) { - var serviceCollection = new ServiceCollection(); - serviceCollection - .AddEntityFramework() - .AddSqlServer(); - - var serviceProvider = serviceCollection.BuildServiceProvider(); - - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); - - using (var context = new NorthwindContext(serviceProvider, optionsBuilder.Options)) + using (var context = new NorthwindContext(new DbContextOptionsBuilder() + .UseSqlServer(SqlServerNorthwindContext.ConnectionString) + .UseInternalServiceProvider(new ServiceCollection() + .AddEntityFramework() + .AddSqlServer() + .BuildServiceProvider()).Options)) { Assert.Equal(91, await context.Customers.CountAsync()); } @@ -145,17 +128,15 @@ public async Task Can_query_with_explicit_services_and_explicit_config() private class NorthwindContext : DbContext { - public NorthwindContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public NorthwindContext(DbContextOptions options) + : base(options) { } public DbSet Customers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); } } @@ -166,18 +147,15 @@ public void Throws_on_attempt_to_use_SQL_Server_without_providing_connection_str { using (SqlServerNorthwindContext.GetSharedStore()) { - var serviceCollection = new ServiceCollection(); - serviceCollection - .AddEntityFramework() - .AddSqlServer(); - - var serviceProvider = serviceCollection.BuildServiceProvider(); - Assert.Equal( CoreStrings.NoProviderConfigured, Assert.Throws(() => { - using (var context = new NorthwindContext(serviceProvider)) + using (var context = new NorthwindContext( + new DbContextOptionsBuilder().UseInternalServiceProvider(new ServiceCollection() + .AddEntityFramework() + .AddSqlServer() + .BuildServiceProvider()).Options)) { Assert.Equal(91, context.Customers.Count()); } @@ -187,17 +165,15 @@ public void Throws_on_attempt_to_use_SQL_Server_without_providing_connection_str private class NorthwindContext : DbContext { - public NorthwindContext(IServiceProvider serviceProvider) - : base(serviceProvider) + public NorthwindContext(DbContextOptions options) + : base(options) { } public DbSet Customers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); } } @@ -225,9 +201,7 @@ private class NorthwindContext : DbContext public DbSet Customers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); } } @@ -238,17 +212,15 @@ public void Throws_on_attempt_to_use_store_with_no_store_services() { using (SqlServerNorthwindContext.GetSharedStore()) { - var serviceCollection = new ServiceCollection(); - serviceCollection - .AddEntityFramework(); - - var serviceProvider = serviceCollection.BuildServiceProvider(); - Assert.Equal( - CoreStrings.NoProviderServices, + CoreStrings.NoProviderConfigured, Assert.Throws(() => { - using (var context = new NorthwindContext(serviceProvider)) + using (var context = new NorthwindContext( + new DbContextOptionsBuilder() + .UseInternalServiceProvider(new ServiceCollection() + .AddEntityFramework() + .BuildServiceProvider()).Options)) { Assert.Equal(91, context.Customers.Count()); } @@ -258,22 +230,18 @@ public void Throws_on_attempt_to_use_store_with_no_store_services() private class NorthwindContext : DbContext { - public NorthwindContext(IServiceProvider serviceProvider) - : base(serviceProvider) + public NorthwindContext(DbContextOptions options) + : base(options) { } public DbSet Customers { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); - } protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); } } @@ -282,14 +250,12 @@ public class InjectContext [Fact] public async Task Can_register_context_with_DI_container_and_have_it_injected() { - var serviceCollection = new ServiceCollection(); - serviceCollection + var serviceProvider = new ServiceCollection() .AddEntityFramework() - .AddSqlServer(); - - var serviceProvider = serviceCollection + .AddSqlServer() .AddTransient() .AddTransient() + .AddSingleton(p => new DbContextOptionsBuilder().UseInternalServiceProvider(p).Options) .BuildServiceProvider(); using (SqlServerNorthwindContext.GetSharedStore()) @@ -310,30 +276,24 @@ public MyController(NorthwindContext context) } public async Task TestAsync() - { - Assert.Equal(91, await _context.Customers.CountAsync()); - } + => Assert.Equal(91, await _context.Customers.CountAsync()); } private class NorthwindContext : DbContext { - public NorthwindContext(IServiceProvider serviceProvider) - : base(serviceProvider) + public NorthwindContext(DbContextOptions options) + : base(options) { - Assert.NotNull(serviceProvider); + Assert.NotNull(options); } public DbSet Customers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); - } + => optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); } } @@ -342,19 +302,11 @@ public class InjectContextAndConfiguration [Fact] public async Task Can_register_context_and_configuration_with_DI_container_and_have_both_injected() { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); - - var serviceCollection = new ServiceCollection(); - serviceCollection - .AddEntityFramework() - .AddSqlServer(); - - serviceCollection + var serviceProvider = new ServiceCollection() .AddTransient() .AddTransient() - .AddSingleton(optionsBuilder.Options); - var serviceProvider = serviceCollection.BuildServiceProvider(); + .AddSingleton(new DbContextOptionsBuilder() + .UseSqlServer(SqlServerNorthwindContext.ConnectionString).Options).BuildServiceProvider(); using (SqlServerNorthwindContext.GetSharedStore()) { @@ -374,72 +326,7 @@ public MyController(NorthwindContext context) } public async Task TestAsync() - { - Assert.Equal(91, await _context.Customers.CountAsync()); - } - } - - private class NorthwindContext : DbContext - { - public NorthwindContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) - { - Assert.NotNull(serviceProvider); - Assert.NotNull(options); - } - - public DbSet Customers { get; set; } - - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } - } - } - - public class InjectConfiguration - { - // This one is a bit strange because the context gets the configuration from the service provider - // but doesn't get the service provider and so creates a new one for use internally. This works fine - // although it would be much more common to inject both when using DI explicitly. - [Fact] - public async Task Can_register_configuration_with_DI_container_and_have_it_injected() - { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); - - var serviceCollection = new ServiceCollection(); - serviceCollection - .AddEntityFramework() - .AddSqlServer(); - - serviceCollection - .AddTransient() - .AddTransient() - .AddSingleton(optionsBuilder.Options); - var serviceProvider = serviceCollection.BuildServiceProvider(); - - using (SqlServerNorthwindContext.GetSharedStore()) - { - await serviceProvider.GetRequiredService().TestAsync(); - } - } - - private class MyController - { - private readonly NorthwindContext _context; - - public MyController(NorthwindContext context) - { - Assert.NotNull(context); - - _context = context; - } - - public async Task TestAsync() - { - Assert.Equal(91, await _context.Customers.CountAsync()); - } + => Assert.Equal(91, await _context.Customers.CountAsync()); } private class NorthwindContext : DbContext @@ -453,9 +340,7 @@ public NorthwindContext(DbContextOptions options) public DbSet Customers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); } } @@ -466,10 +351,8 @@ public async Task Can_pass_context_options_to_constructor_and_use_in_builder() { using (SqlServerNorthwindContext.GetSharedStore()) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); - - using (var context = new NorthwindContext(optionsBuilder.Options)) + using (var context = new NorthwindContext(new DbContextOptionsBuilder() + .UseSqlServer(SqlServerNorthwindContext.ConnectionString).Options)) { Assert.Equal(91, await context.Customers.CountAsync()); } @@ -486,9 +369,7 @@ public NorthwindContext(DbContextOptions options) public DbSet Customers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); } } @@ -518,14 +399,10 @@ public NorthwindContext(string connectionString) public DbSet Customers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(_connectionString); - } + => optionsBuilder.UseSqlServer(_connectionString); protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); } } @@ -536,12 +413,10 @@ public async Task Can_use_one_context_nested_inside_another_of_the_same_type() { using (SqlServerNorthwindContext.GetSharedStore()) { - var serviceCollection = new ServiceCollection(); - serviceCollection + var serviceProvider = new ServiceCollection() .AddEntityFramework() - .AddSqlServer(); - - var serviceProvider = serviceCollection.BuildServiceProvider(); + .AddSqlServer() + .BuildServiceProvider(); using (var context1 = new NorthwindContext(serviceProvider)) { @@ -566,22 +441,21 @@ public async Task Can_use_one_context_nested_inside_another_of_the_same_type() private class NorthwindContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public NorthwindContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Customers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); - } + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder + .UseInternalServiceProvider(_serviceProvider) + .UseSqlServer(SqlServerNorthwindContext.ConnectionString); } } @@ -592,13 +466,11 @@ public async Task Can_use_one_context_nested_inside_another_of_a_different_type( { using (SqlServerNorthwindContext.GetSharedStore()) { - var serviceCollection = new ServiceCollection(); - serviceCollection + var serviceProvider = new ServiceCollection() .AddEntityFramework() .AddSqlServer() - .AddInMemoryDatabase(); - - var serviceProvider = serviceCollection.BuildServiceProvider(); + .AddInMemoryDatabase() + .BuildServiceProvider(); await NestedContextTest(() => new BlogContext(serviceProvider), () => new NorthwindContext(serviceProvider)); } @@ -649,45 +521,47 @@ private async Task NestedContextTest(Func createBlogContext, Func Blogs { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseInMemoryDatabase(); - } + => optionsBuilder + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); } private class NorthwindContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public NorthwindContext() { } public NorthwindContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Customers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) - { - ConfigureModel(modelBuilder); - } + => ConfigureModel(modelBuilder); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); - } + => optionsBuilder + .UseSqlServer(SqlServerNorthwindContext.ConnectionString) + .UseInternalServiceProvider(_serviceProvider); } } @@ -705,12 +579,10 @@ private class Customer } private static void ConfigureModel(ModelBuilder builder) - { - builder.Entity(b => + => builder.Entity(b => { b.HasKey(c => c.CustomerID); b.ForSqlServerToTable("Customers"); }); - } } } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerDatabaseCreationTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerDatabaseCreationTest.cs index 6feac5a20d4..063d2c2e164 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerDatabaseCreationTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerDatabaseCreationTest.cs @@ -310,15 +310,14 @@ private class BloggingContext : DbContext private readonly SqlServerTestStore _testStore; public BloggingContext(SqlServerTestStore testStore) - : base(CreateServiceProvider()) { _testStore = testStore; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(_testStore.ConnectionString); - } + => optionsBuilder + .UseSqlServer(_testStore.ConnectionString) + .UseInternalServiceProvider(CreateServiceProvider()); protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs index 887c047ac0d..3b21c85fee9 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs @@ -221,17 +221,16 @@ private static async Task CreateTables_creates_schema_in_existing_database_test( { using (var testDatabase = await SqlServerTestStore.CreateScratchAsync()) { - var serviceCollection = new ServiceCollection(); - serviceCollection + var serviceProvider = new ServiceCollection() .AddEntityFramework() - .AddSqlServer(); + .AddSqlServer() + .BuildServiceProvider(); - var serviceProvider = serviceCollection.BuildServiceProvider(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseInternalServiceProvider(serviceProvider) + .UseSqlServer(testDatabase.ConnectionString); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(testDatabase.ConnectionString); - - using (var context = new BloggingContext(serviceProvider, optionsBuilder.Options)) + using (var context = new BloggingContext(optionsBuilder.Options)) { var creator = (RelationalDatabaseCreator)context.GetService(); @@ -367,30 +366,22 @@ private static async Task Create_throws_if_database_already_exists_test(bool asy } private static IServiceProvider CreateContextServices(SqlServerTestStore testStore) - { - var serviceCollection = new ServiceCollection(); - serviceCollection - .AddEntityFramework() - .AddSqlServer(); - - serviceCollection.AddScoped(); - - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(testStore.ConnectionString); - - return ((IInfrastructure)new BloggingContext( - serviceCollection.BuildServiceProvider(), - optionsBuilder.Options)) + => ((IInfrastructure)new BloggingContext( + new DbContextOptionsBuilder() + .UseSqlServer(testStore.ConnectionString) + .UseInternalServiceProvider(new ServiceCollection() + .AddEntityFramework() + .AddSqlServer() + .AddScoped().BuildServiceProvider()).Options)) .Instance; - } private static IRelationalDatabaseCreator GetDatabaseCreator(SqlServerTestStore testStore) => CreateContextServices(testStore).GetRequiredService(); private class BloggingContext : DbContext { - public BloggingContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public BloggingContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs index b7d809b997d..8b2d3352f28 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs @@ -111,24 +111,24 @@ public async Task Can_save_changes() { using (var testDatabase = await SqlServerTestStore.CreateScratchAsync()) { - var optionsBuilder = new DbContextOptionsBuilder(); + var loggingFactory = new TestSqlLoggerFactory(); + var serviceProvider = new ServiceCollection() + .AddEntityFramework() + .AddSqlServer() + .AddSingleton(loggingFactory) + .BuildServiceProvider(); - optionsBuilder + var optionsBuilder = new DbContextOptionsBuilder() .EnableSensitiveDataLogging() - .UseSqlServer(testDatabase.ConnectionString); + .UseSqlServer(testDatabase.ConnectionString) + .UseInternalServiceProvider(serviceProvider); - using (var db = new BloggingContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var db = new BloggingContext(optionsBuilder.Options)) { await CreateBlogDatabaseAsync(db); } - var loggingFactory = new TestSqlLoggerFactory(); - var serviceProvider = new ServiceCollection() - .AddEntityFramework() - .AddSqlServer() - .AddSingleton(loggingFactory) - .BuildServiceProvider(); - using (var db = new BloggingContext(serviceProvider, optionsBuilder.Options)) + using (var db = new BloggingContext(optionsBuilder.Options)) { var toUpdate = db.Blogs.Single(b => b.Name == "Blog1"); toUpdate.Name = "Blog is Updated"; @@ -198,13 +198,14 @@ public async Task Can_save_changes_in_tracked_entities() { using (var testDatabase = await SqlServerTestStore.CreateScratchAsync()) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(testDatabase.ConnectionString); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(testDatabase.ConnectionString) + .UseInternalServiceProvider(_fixture.ServiceProvider); int updatedId; int deletedId; int addedId; - using (var db = new BloggingContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var db = new BloggingContext(optionsBuilder.Options)) { var blogs = await CreateBlogDatabaseAsync(db); @@ -243,7 +244,7 @@ public async Task Can_save_changes_in_tracked_entities() Assert.DoesNotContain(toDelete, db.ChangeTracker.Entries().Select(e => e.Entity)); } - using (var db = new BloggingContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var db = new BloggingContext(optionsBuilder.Options)) { var toUpdate = db.Blogs.Single(b => b.Id == updatedId); Assert.Equal("Blog is Updated", toUpdate.Name); @@ -307,9 +308,11 @@ var serviceProvider private class SchemaContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public SchemaContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbConnection Connection { get; set; } @@ -317,10 +320,8 @@ public SchemaContext(IServiceProvider serviceProvider) public DbSet Jacks { get; set; } public DbSet Blacks { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(Connection); - } + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder.UseSqlServer(Connection).UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -368,14 +369,15 @@ public async Task Can_round_trip_changes_with_changed_only_notification_entities { using (var testDatabase = await SqlServerTestStore.CreateScratchAsync()) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(testDatabase.ConnectionString); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(testDatabase.ConnectionString) + .UseInternalServiceProvider(_fixture.ServiceProvider); int blog1Id; int blog2Id; int blog3Id; - using (var context = new BloggingContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new BloggingContext(optionsBuilder.Options)) { var blogs = await CreateBlogDatabaseAsync(context); blog1Id = blogs[0].Id; @@ -386,7 +388,7 @@ public async Task Can_round_trip_changes_with_changed_only_notification_entities Assert.NotEqual(blog1Id, blog2Id); } - using (var context = new BloggingContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new BloggingContext(optionsBuilder.Options)) { var blogs = context.Blogs.ToList(); Assert.Equal(2, blogs.Count); @@ -422,7 +424,7 @@ public async Task Can_round_trip_changes_with_changed_only_notification_entities Assert.NotEqual(0, blog3Id); } - using (var context = new BloggingContext(_fixture.ServiceProvider, optionsBuilder.Options)) + using (var context = new BloggingContext(optionsBuilder.Options)) { var blogs = context.Blogs.ToList(); Assert.Equal(3, blogs.Count); @@ -495,17 +497,19 @@ public SqlServerEndToEndTest(SqlServerFixture fixture) private class NorthwindContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public NorthwindContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Customers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString); - } + => optionsBuilder + .UseSqlServer(SqlServerNorthwindContext.ConnectionString) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -526,8 +530,8 @@ private class Customer private class BloggingContext : BloggingContext { - public BloggingContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public BloggingContext(DbContextOptions options) + : base(options) { } } @@ -555,15 +559,13 @@ private class Blog : IBlog private class BloggingContext : DbContext where TBlog : class, IBlog { - public BloggingContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public BloggingContext(DbContextOptions options) + : base(options) { } - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity().ToTable("Blog", "dbo"); - } + protected override void OnModelCreating(ModelBuilder modelBuilder) + => modelBuilder.Entity().ToTable("Blog", "dbo"); public DbSet Blogs { get; set; } } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerMigrationsTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerMigrationsTest.cs index c26c9f2f0d1..fedf0b2c6a8 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerMigrationsTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerMigrationsTest.cs @@ -37,16 +37,17 @@ private static BloggingContext CreateContext(SqlServerTestStore testStore) .AddSqlServer() .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(testStore.ConnectionString); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(testStore.ConnectionString) + .UseInternalServiceProvider(serviceProvider); - return new BloggingContext(serviceProvider, optionsBuilder.Options); + return new BloggingContext(optionsBuilder.Options); } private class BloggingContext : DbContext { - public BloggingContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public BloggingContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerTriggersTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerTriggersTest.cs index d70880d1223..31acbdb7d08 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerTriggersTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/SqlServerTriggersTest.cs @@ -166,20 +166,16 @@ DELETE FROM ProductBackups } public TriggersContext CreateContext(SqlServerTestStore testStore) - { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder + => new TriggersContext(new DbContextOptionsBuilder() .EnableSensitiveDataLogging() - .UseSqlServer(testStore.Connection); - - return new TriggersContext(_serviceProvider, optionsBuilder.Options); - } + .UseInternalServiceProvider(_serviceProvider) + .UseSqlServer(testStore.Connection).Options); } public class TriggersContext : DbContext { - public TriggersContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public TriggersContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/StoreGeneratedSqlServerTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/StoreGeneratedSqlServerTest.cs index 326c6c07953..03c4d8eb5f5 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/StoreGeneratedSqlServerTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/StoreGeneratedSqlServerTest.cs @@ -35,10 +35,11 @@ public override SqlServerTestStore CreateTestStore() { return SqlServerTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString(DatabaseName)); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(SqlServerTestStore.CreateConnectionString(DatabaseName)) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new StoreGeneratedContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new StoreGeneratedContext(optionsBuilder.Options)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); @@ -48,10 +49,11 @@ public override SqlServerTestStore CreateTestStore() public override DbContext CreateContext(SqlServerTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(testStore.Connection); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(testStore.Connection) + .UseInternalServiceProvider(_serviceProvider); - var context = new StoreGeneratedContext(_serviceProvider, optionsBuilder.Options); + var context = new StoreGeneratedContext(optionsBuilder.Options); context.Database.UseTransaction(testStore.Transaction); return context; diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/TestModels/SqlServerNorthwindContext.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/TestModels/SqlServerNorthwindContext.cs index 333d0c57439..0f6a028349c 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/TestModels/SqlServerNorthwindContext.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/TestModels/SqlServerNorthwindContext.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.EntityFrameworkCore.FunctionalTests.TestModels.Northwind; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests.Utilities; @@ -13,8 +12,8 @@ public class SqlServerNorthwindContext : NorthwindContext public static readonly string DatabaseName = StoreName; public static readonly string ConnectionString = SqlServerTestStore.CreateConnectionString(DatabaseName); - public SqlServerNorthwindContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public SqlServerNorthwindContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/TransactionSqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/TransactionSqlServerFixture.cs index 52ec8468367..f0d78a218b2 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/TransactionSqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/TransactionSqlServerFixture.cs @@ -47,19 +47,13 @@ public override SqlServerTestStore CreateTestStore() } public override DbContext CreateContext(SqlServerTestStore testStore) - { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(testStore.ConnectionString); - - return new DbContext(_serviceProvider, optionsBuilder.Options); - } + => new DbContext(new DbContextOptionsBuilder() + .UseSqlServer(testStore.ConnectionString) + .UseInternalServiceProvider(_serviceProvider).Options); public override DbContext CreateContext(DbConnection connection) - { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(connection); - - return new DbContext(_serviceProvider, optionsBuilder.Options); - } + => new DbContext(new DbContextOptionsBuilder() + .UseSqlServer(connection) + .UseInternalServiceProvider(_serviceProvider).Options); } } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/UpdatesSqlServerFixture.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/UpdatesSqlServerFixture.cs index 2314d88c2a3..877174da541 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/UpdatesSqlServerFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests/UpdatesSqlServerFixture.cs @@ -26,27 +26,29 @@ public UpdatesSqlServerFixture() public override SqlServerTestStore CreateTestStore() { return SqlServerTestStore.GetOrCreateShared(DatabaseName, () => - { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(SqlServerTestStore.CreateConnectionString(DatabaseName)); - - using (var context = new UpdatesContext(_serviceProvider, optionsBuilder.Options)) { - context.Database.EnsureDeleted(); - if (context.Database.EnsureCreated()) + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(SqlServerTestStore.CreateConnectionString(DatabaseName)) + .UseInternalServiceProvider(_serviceProvider); + + using (var context = new UpdatesContext(optionsBuilder.Options)) { - UpdatesModelInitializer.Seed(context); + context.Database.EnsureDeleted(); + if (context.Database.EnsureCreated()) + { + UpdatesModelInitializer.Seed(context); + } } - } - }); + }); } public override UpdatesContext CreateContext(SqlServerTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(testStore.Connection); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlServer(testStore.Connection) + .UseInternalServiceProvider(_serviceProvider); - var context = new UpdatesContext(_serviceProvider, optionsBuilder.Options); + var context = new UpdatesContext(optionsBuilder.Options); context.Database.UseTransaction(testStore.Transaction); return context; } diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/CommandConfigurationTests.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/CommandConfigurationTests.cs index 64604219d59..7a4ebb9cec6 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/CommandConfigurationTests.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/CommandConfigurationTests.cs @@ -30,9 +30,10 @@ public void Default_value_for_CommandTimeout_is_null_and_can_be_changed_includin [Fact] public void Setting_CommandTimeout_to_negative_value_throws() { - var optionsBuilder = new DbContextOptionsBuilder().UseSqlServer("No=LoveyDovey"); - - Assert.Throws(() => optionsBuilder.CommandTimeout(-55)); + Assert.Throws( + () => new DbContextOptionsBuilder().UseSqlServer( + "No=LoveyDovey", + b => b.CommandTimeout(-55))); using (var context = new TimeoutContext()) { diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/SqlServerConnectionTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/SqlServerConnectionTest.cs index c527b68fa62..3de15fbce76 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/SqlServerConnectionTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/SqlServerConnectionTest.cs @@ -37,8 +37,9 @@ public void Can_create_master_connection() public void Master_connection_string_none_default_command_timeout() { var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=SqlServerConnectionTest;Trusted_Connection=True;") - .CommandTimeout(55); + optionsBuilder.UseSqlServer( + @"Server=(localdb)\MSSQLLocalDB;Database=SqlServerConnectionTest;Trusted_Connection=True;", + b => b.CommandTimeout(55)); using (var connection = new SqlServerConnection(optionsBuilder.Options, new Logger(new LoggerFactory()))) { diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/SqlServerDbContextOptionsExtensionsTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/SqlServerDbContextOptionsExtensionsTest.cs index 52adcf9be5a..41ea251a0d0 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/SqlServerDbContextOptionsExtensionsTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/SqlServerDbContextOptionsExtensionsTest.cs @@ -3,7 +3,6 @@ using System.Data.SqlClient; using System.Linq; -using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure.Internal; using Xunit; @@ -15,7 +14,7 @@ public class SqlServerDbContextOptionsExtensionsTest public void Can_add_extension_with_max_batch_size() { var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer("Database=Crunchie").MaxBatchSize(123); + optionsBuilder.UseSqlServer("Database=Crunchie", b => b.MaxBatchSize(123)); var extension = optionsBuilder.Options.Extensions.OfType().Single(); @@ -26,7 +25,7 @@ public void Can_add_extension_with_max_batch_size() public void Can_add_extension_with_command_timeout() { var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer("Database=Crunchie").CommandTimeout(30); + optionsBuilder.UseSqlServer("Database=Crunchie", b => b.CommandTimeout(30)); var extension = optionsBuilder.Options.Extensions.OfType().Single(); @@ -37,7 +36,7 @@ public void Can_add_extension_with_command_timeout() public void Can_add_extension_with_ambient_transaction_warning_suppressed() { var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer("Database=Crunchie").SuppressAmbientTransactionWarning(); + optionsBuilder.UseSqlServer("Database=Crunchie", b => b.SuppressAmbientTransactionWarning()); var extension = optionsBuilder.Options.Extensions.OfType().Single(); @@ -101,7 +100,7 @@ public void Can_add_extension_with_legacy_paging() { var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer("Database=Kilimanjaro").UseRowNumberForPaging(); + optionsBuilder.UseSqlServer("Database=Kilimanjaro", b => b.UseRowNumberForPaging()); var extension = optionsBuilder.Options.Extensions.OfType().Single(); diff --git a/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/Update/SqlServerModificationCommandBatchFactoryTest.cs b/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/Update/SqlServerModificationCommandBatchFactoryTest.cs index ceec06c096f..f9575e324c7 100644 --- a/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/Update/SqlServerModificationCommandBatchFactoryTest.cs +++ b/test/Microsoft.EntityFrameworkCore.SqlServer.Tests/Update/SqlServerModificationCommandBatchFactoryTest.cs @@ -17,7 +17,7 @@ public class SqlServerModificationCommandBatchFactoryTest public void Uses_MaxBatchSize_specified_in_SqlServerOptionsExtension() { var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlServer("Database=Crunchie").MaxBatchSize(1); + optionsBuilder.UseSqlServer("Database=Crunchie", b => b.MaxBatchSize(1)); var factory = new SqlServerModificationCommandBatchFactory( new RelationalCommandBuilderFactory( diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/AutoincrementTest.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/AutoincrementTest.cs index ece14aa008e..38554d15021 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/AutoincrementTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/AutoincrementTest.cs @@ -42,7 +42,7 @@ public void Autoincrement_prevents_reusing_rowid() [Fact] public void Identity_metadata_not_on_text_is_ignored() { - using (var context = new JokerContext(_provider, _options)) + using (var context = new JokerContext(_options)) { context.Database.EnsureCreated(); } @@ -52,24 +52,26 @@ public AutoincrementTest() { _testStore = SqliteTestStore.CreateScratch(); - var builder = new DbContextOptionsBuilder(); - builder.UseSqlite(_testStore.Connection); - _options = builder.Options; _provider = new ServiceCollection() .AddEntityFramework() .AddSqlite() .BuildServiceProvider(); + + _options = new DbContextOptionsBuilder() + .UseInternalServiceProvider(_provider) + .UseSqlite(_testStore.Connection) + .Options; } - private BatContext CreateContext() => new BatContext(_provider, _options); + private BatContext CreateContext() => new BatContext(_options); public void Dispose() => _testStore.Dispose(); } public class JokerContext : DbContext { - public JokerContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public JokerContext(DbContextOptions options) + : base(options) { } @@ -88,8 +90,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public class BatContext : DbContext { - public BatContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public BatContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/BuiltInDataTypesSqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/BuiltInDataTypesSqliteFixture.cs index 8cd13f3b69c..c572d8bfe39 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/BuiltInDataTypesSqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/BuiltInDataTypesSqliteFixture.cs @@ -24,12 +24,12 @@ public BuiltInDataTypesSqliteFixture() .AddSingleton(TestSqliteModelSource.GetFactory(OnModelCreating)) .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(_testStore.Connection); + _options = new DbContextOptionsBuilder() + .UseSqlite(_testStore.Connection) + .UseInternalServiceProvider(_serviceProvider) + .Options; - _options = optionsBuilder.Options; - - using (var context = new DbContext(_serviceProvider, _options)) + using (var context = new DbContext(_options)) { context.Database.EnsureCreated(); } @@ -37,7 +37,7 @@ public BuiltInDataTypesSqliteFixture() public override DbContext CreateContext() { - var context = new DbContext(_serviceProvider, _options); + var context = new DbContext(_options); context.Database.UseTransaction(_testStore.Transaction); return context; } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/CommandConfigurationTest.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/CommandConfigurationTest.cs index 97d33891576..79e65072ddc 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/CommandConfigurationTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/CommandConfigurationTest.cs @@ -41,10 +41,7 @@ public virtual void CreateDatabase() }); } - public void Dispose() - { - _store.Dispose(); - } + public void Dispose() => _store.Dispose(); } [Fact] @@ -58,17 +55,19 @@ public void Constructed_select_query_CommandBuilder_throws_when_negative_Command private class ChipsContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public ChipsContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Chips { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlite(SqliteTestStore.CreateConnectionString(DatabaseName)); - } + => optionsBuilder + .UseSqlite(SqliteTestStore.CreateConnectionString(DatabaseName)) + .UseInternalServiceProvider(_serviceProvider); } private class KettleChips diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/ComplexNavigationsQuerySqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/ComplexNavigationsQuerySqliteFixture.cs index 1c90a26cfa8..ffc1dc69629 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/ComplexNavigationsQuerySqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/ComplexNavigationsQuerySqliteFixture.cs @@ -2,7 +2,6 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.FunctionalTests; using Microsoft.EntityFrameworkCore.FunctionalTests.TestModels.ComplexNavigationsModel; using Microsoft.Extensions.DependencyInjection; @@ -33,10 +32,11 @@ public override SqliteTestStore CreateTestStore() => DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(_connectionString); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(_connectionString) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new ComplexNavigationsContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new ComplexNavigationsContext(optionsBuilder.Options)) { // TODO: Delete DB if model changed context.Database.EnsureDeleted(); @@ -51,11 +51,13 @@ public override SqliteTestStore CreateTestStore() => public override ComplexNavigationsContext CreateContext(SqliteTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(testStore.Connection) - .SuppressForeignKeyEnforcement(); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite( + testStore.Connection, + b => b.SuppressForeignKeyEnforcement()) + .UseInternalServiceProvider(_serviceProvider); - var context = new ComplexNavigationsContext(_serviceProvider, optionsBuilder.Options); + var context = new ComplexNavigationsContext(optionsBuilder.Options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/CompositeKeyEndToEndTest.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/CompositeKeyEndToEndTest.cs index 75d2ca4bff0..ec06b675afa 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/CompositeKeyEndToEndTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/CompositeKeyEndToEndTest.cs @@ -117,19 +117,22 @@ public async Task Only_one_part_of_a_composite_key_needs_to_vary_for_uniqueness( private class BronieContext : DbContext { + private readonly IServiceProvider _serviceProvider; private readonly string _databaseName; public BronieContext(IServiceProvider serviceProvider, string databaseName) - : base(serviceProvider) { + _serviceProvider = serviceProvider; _databaseName = databaseName; } public DbSet Pegasuses { get; set; } public DbSet EarthPonies { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseSqlite(SqliteTestStore.CreateConnectionString(_databaseName)); + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder + .UseSqlite(SqliteTestStore.CreateConnectionString(_databaseName)) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/DataAnnotationSqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/DataAnnotationSqliteFixture.cs index 77147d2cdda..0a947e418ae 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/DataAnnotationSqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/DataAnnotationSqliteFixture.cs @@ -27,13 +27,13 @@ public DataAnnotationSqliteFixture() } public override SqliteTestStore CreateTestStore() - { - return SqliteTestStore.GetOrCreateShared(DatabaseName, () => + => SqliteTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(_connectionString); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(_connectionString) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new DataAnnotationContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new DataAnnotationContext(optionsBuilder.Options)) { // TODO: Delete DB if model changed context.Database.EnsureDeleted(); @@ -45,18 +45,17 @@ public override SqliteTestStore CreateTestStore() TestSqlLoggerFactory.SqlStatements.Clear(); } }); - } public override DataAnnotationContext CreateContext(SqliteTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - - optionsBuilder + var optionsBuilder = new DbContextOptionsBuilder() .EnableSensitiveDataLogging() - .UseSqlite(testStore.Connection) - .SuppressForeignKeyEnforcement(); + .UseSqlite( + testStore.Connection, + b => b.SuppressForeignKeyEnforcement()) + .UseInternalServiceProvider(_serviceProvider); - var context = new DataAnnotationContext(_serviceProvider, optionsBuilder.Options); + var context = new DataAnnotationContext(optionsBuilder.Options); context.Database.UseTransaction(testStore.Transaction); return context; } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/DefaultValuesTest.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/DefaultValuesTest.cs index f6551ab63cd..ce57e9ea717 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/DefaultValuesTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/DefaultValuesTest.cs @@ -50,20 +50,21 @@ public void Dispose() private class ChipsContext : DbContext { + private readonly IServiceProvider _serviceProvider; private readonly string _databaseName; public ChipsContext(IServiceProvider serviceProvider, string databaseName) - : base(serviceProvider) { + _serviceProvider = serviceProvider; _databaseName = databaseName; } public DbSet Chips { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseSqlite(SqliteTestStore.CreateConnectionString(_databaseName)); - } + => optionsBuilder + .UseSqlite(SqliteTestStore.CreateConnectionString(_databaseName)) + .UseInternalServiceProvider(_serviceProvider); protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/F1SqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/F1SqliteFixture.cs index 62ee01d8565..90805840020 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/F1SqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/F1SqliteFixture.cs @@ -31,10 +31,11 @@ public override SqliteTestStore CreateTestStore() { return SqliteTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(_connectionString); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(_connectionString) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new F1Context(_serviceProvider, optionsBuilder.Options)) + using (var context = new F1Context(optionsBuilder.Options)) { // TODO: Delete DB if model changed context.Database.EnsureDeleted(); @@ -50,10 +51,11 @@ public override SqliteTestStore CreateTestStore() public override F1Context CreateContext(SqliteTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(testStore.Connection); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(testStore.Connection) + .UseInternalServiceProvider(_serviceProvider); - var context = new F1Context(_serviceProvider, optionsBuilder.Options); + var context = new F1Context(optionsBuilder.Options); context.Database.UseTransaction(testStore.Transaction); return context; } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/GearsOfWarQuerySqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/GearsOfWarQuerySqliteFixture.cs index c890b0ad653..614f06e3c3d 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/GearsOfWarQuerySqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/GearsOfWarQuerySqliteFixture.cs @@ -32,10 +32,11 @@ public override SqliteTestStore CreateTestStore() { return SqliteTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(_connectionString); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(_connectionString) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new GearsOfWarContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new GearsOfWarContext(optionsBuilder.Options)) { // TODO: Delete DB if model changed context.Database.EnsureDeleted(); @@ -51,10 +52,11 @@ public override SqliteTestStore CreateTestStore() public override GearsOfWarContext CreateContext(SqliteTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(testStore.Connection); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(testStore.Connection) + .UseInternalServiceProvider(_serviceProvider); - var context = new GearsOfWarContext(_serviceProvider, optionsBuilder.Options); + var context = new GearsOfWarContext(optionsBuilder.Options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/GraphUpdatesSqliteTest.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/GraphUpdatesSqliteTest.cs index 46c67572929..38fd6772fe6 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/GraphUpdatesSqliteTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/GraphUpdatesSqliteTest.cs @@ -34,10 +34,11 @@ public override SqliteTestStore CreateTestStore() { return SqliteTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(SqliteTestStore.CreateConnectionString(DatabaseName)); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(SqliteTestStore.CreateConnectionString(DatabaseName)) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new GraphUpdatesContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new GraphUpdatesContext(optionsBuilder.Options)) { context.Database.EnsureDeleted(); if (context.Database.EnsureCreated()) @@ -50,10 +51,11 @@ public override SqliteTestStore CreateTestStore() public override DbContext CreateContext(SqliteTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(testStore.Connection); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(testStore.Connection) + .UseInternalServiceProvider(_serviceProvider); - var context = new GraphUpdatesContext(_serviceProvider, optionsBuilder.Options); + var context = new GraphUpdatesContext(optionsBuilder.Options); context.Database.UseTransaction(testStore.Transaction); return context; } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/InheritanceRelationshipsQuerySqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/InheritanceRelationshipsQuerySqliteFixture.cs index c72d9b33497..b87fb2914ce 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/InheritanceRelationshipsQuerySqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/InheritanceRelationshipsQuerySqliteFixture.cs @@ -25,10 +25,11 @@ public InheritanceRelationshipsQuerySqliteFixture() public override InheritanceRelationshipsContext CreateContext(SqliteTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(testStore.Connection); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(testStore.Connection) + .UseInternalServiceProvider(_serviceProvider); - var context = new InheritanceRelationshipsContext(_serviceProvider, optionsBuilder.Options); + var context = new InheritanceRelationshipsContext(optionsBuilder.Options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; @@ -41,11 +42,12 @@ public override SqliteTestStore CreateTestStore() => SqliteTestStore.GetOrCreateShared( nameof(InheritanceRelationshipsQuerySqliteTest), () => - { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(SqliteTestStore.CreateConnectionString(nameof(InheritanceRelationshipsQuerySqliteTest))); + { + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(SqliteTestStore.CreateConnectionString(nameof(InheritanceRelationshipsQuerySqliteTest))) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new InheritanceRelationshipsContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new InheritanceRelationshipsContext(optionsBuilder.Options)) { // TODO: Delete DB if model changed context.Database.EnsureDeleted(); diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/InheritanceSqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/InheritanceSqliteFixture.cs index c0f0e3e3157..d72d9b1544a 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/InheritanceSqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/InheritanceSqliteFixture.cs @@ -13,24 +13,21 @@ namespace Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests public class InheritanceSqliteFixture : InheritanceRelationalFixture, IDisposable { private readonly DbContextOptions _options; - private readonly IServiceProvider _serviceProvider; private readonly SqliteTestStore _testStore; public InheritanceSqliteFixture() { - _serviceProvider - = new ServiceCollection() + _testStore = SqliteTestStore.CreateScratch(); + + _options = new DbContextOptionsBuilder() + .UseSqlite(_testStore.Connection) + .UseInternalServiceProvider(new ServiceCollection() .AddEntityFramework() .AddSqlite() .AddSingleton(TestSqliteModelSource.GetFactory(OnModelCreating)) .AddSingleton(new TestSqlLoggerFactory()) - .BuildServiceProvider(); - - _testStore = SqliteTestStore.CreateScratch(); - - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(_testStore.Connection); - _options = optionsBuilder.Options; + .BuildServiceProvider()) + .Options; // TODO: Do this via migrations & update pipeline @@ -72,10 +69,11 @@ FOREIGN KEY(countryId) REFERENCES Country(Id) { SeedData(context); } + TestSqlLoggerFactory.Reset(); } - public override InheritanceContext CreateContext() => new InheritanceContext(_serviceProvider, _options); + public override InheritanceContext CreateContext() => new InheritanceContext(_options); public void Dispose() => _testStore.Dispose(); } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/MappingQuerySqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/MappingQuerySqliteFixture.cs index 5448b2802b4..06cec893e89 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/MappingQuerySqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/MappingQuerySqliteFixture.cs @@ -27,15 +27,18 @@ public MappingQuerySqliteFixture() _testDatabase = SqliteNorthwindContext.GetSharedStore(); - var optionsBuilder = new DbContextOptionsBuilder().UseModel(CreateModel()); - optionsBuilder.UseSqlite(_testDatabase.ConnectionString) - .SuppressForeignKeyEnforcement(); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseModel(CreateModel()) + .UseSqlite( + _testDatabase.ConnectionString, + b => b.SuppressForeignKeyEnforcement()) + .UseInternalServiceProvider(_serviceProvider) + .Options; } public DbContext CreateContext() { - var context = new DbContext(_serviceProvider, _options); + var context = new DbContext(_options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/MigrationsSqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/MigrationsSqliteFixture.cs index 60a1823ed1c..78160736977 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/MigrationsSqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/MigrationsSqliteFixture.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using Microsoft.EntityFrameworkCore.FunctionalTests; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; @@ -11,21 +10,20 @@ namespace Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests public class MigrationsSqliteFixture : MigrationsFixtureBase { private readonly DbContextOptions _options; - private readonly IServiceProvider _serviceProvider; public MigrationsSqliteFixture() { - _serviceProvider = new ServiceCollection() + var serviceProvider = new ServiceCollection() .AddEntityFramework() .AddSqlite() .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite("Data Source=" + nameof(MigrationsSqliteTest) + ".db"); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseInternalServiceProvider(serviceProvider) + .UseSqlite("Data Source=" + nameof(MigrationsSqliteTest) + ".db").Options; } public override MigrationsContext CreateContext() - => new MigrationsContext(_serviceProvider, _options); + => new MigrationsContext(_options); } } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NorthwindQuerySqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NorthwindQuerySqliteFixture.cs index c3f67815940..c5b1824d302 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NorthwindQuerySqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NorthwindQuerySqliteFixture.cs @@ -36,24 +36,18 @@ public NorthwindQuerySqliteFixture() } protected DbContextOptions BuildOptions() - { - var optionsBuilder = new DbContextOptionsBuilder(); - - var sqliteDbContextOptionsBuilder - = optionsBuilder.UseSqlite(_testStore.ConnectionString) - .SuppressForeignKeyEnforcement(); + => new DbContextOptionsBuilder() + .UseInternalServiceProvider(_serviceProvider) + .UseSqlite( + _testStore.ConnectionString, + b => ConfigureOptions(b).SuppressForeignKeyEnforcement()) + .Options; - ConfigureOptions(sqliteDbContextOptionsBuilder); - - return optionsBuilder.Options; - } - - protected virtual void ConfigureOptions(SqliteDbContextOptionsBuilder sqliteDbContextOptionsBuilder) - { - } + protected virtual SqliteDbContextOptionsBuilder ConfigureOptions(SqliteDbContextOptionsBuilder sqliteDbContextOptionsBuilder) + => sqliteDbContextOptionsBuilder; public override NorthwindContext CreateContext() - => new SqliteNorthwindContext(_serviceProvider, _options); + => new SqliteNorthwindContext(_options); public void Dispose() => _testStore.Dispose(); diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NotificationEntitiesSqliteTest.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NotificationEntitiesSqliteTest.cs index 1d1e0e6dd9a..24bf1ef6a73 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NotificationEntitiesSqliteTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NotificationEntitiesSqliteTest.cs @@ -29,15 +29,16 @@ public NotificationEntitiesSqliteFixture() .AddSingleton(TestSqliteModelSource.GetFactory(OnModelCreating)) .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(SqliteTestStore.CreateConnectionString("NotificationEntities")); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseSqlite(SqliteTestStore.CreateConnectionString("NotificationEntities")) + .UseInternalServiceProvider(_serviceProvider) + .Options; EnsureCreated(); } public override DbContext CreateContext() - => new DbContext(_serviceProvider, _options); + => new DbContext(_options); } } } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NullKeysSqliteTest.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NullKeysSqliteTest.cs index cd62d0666e9..23e6b713901 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NullKeysSqliteTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NullKeysSqliteTest.cs @@ -28,17 +28,16 @@ public NullKeysSqliteFixture() .AddSingleton(TestSqliteModelSource.GetFactory(OnModelCreating)) .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(SqliteTestStore.CreateConnectionString("StringsContext")); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseSqlite(SqliteTestStore.CreateConnectionString("StringsContext")) + .UseInternalServiceProvider(_serviceProvider) + .Options; EnsureCreated(); } - public override DbContext CreateContext() - { - return new DbContext(_serviceProvider, _options); - } + public override DbContext CreateContext() + => new DbContext(_options); } } } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NullSemanticsQuerySqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NullSemanticsQuerySqliteFixture.cs index 882a311732a..91387b128d5 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NullSemanticsQuerySqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/NullSemanticsQuerySqliteFixture.cs @@ -32,10 +32,11 @@ public override SqliteTestStore CreateTestStore() { return SqliteTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(_connectionString); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(_connectionString) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new NullSemanticsContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new NullSemanticsContext(optionsBuilder.Options)) { // TODO: Delete DB if model changed context.Database.EnsureDeleted(); @@ -52,14 +53,20 @@ public override SqliteTestStore CreateTestStore() public override NullSemanticsContext CreateContext(SqliteTestStore testStore, bool useRelationalNulls) { var optionsBuilder = new DbContextOptionsBuilder(); - var sqliteOptions = optionsBuilder.UseSqlite(testStore.Connection); - - if (useRelationalNulls) - { - sqliteOptions.UseRelationalNulls(); - } + optionsBuilder + .UseInternalServiceProvider(_serviceProvider) + .UseSqlite( + testStore.Connection, + b => + { + if (useRelationalNulls) + { + b.UseRelationalNulls(); + } + } + ); - var context = new NullSemanticsContext(_serviceProvider, optionsBuilder.Options); + var context = new NullSemanticsContext(optionsBuilder.Options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/OneToOneQuerySqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/OneToOneQuerySqliteFixture.cs index 8f67dc7281a..519a9ac85ad 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/OneToOneQuerySqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/OneToOneQuerySqliteFixture.cs @@ -27,11 +27,12 @@ public OneToOneQuerySqliteFixture() _testStore = SqliteTestStore.CreateScratch(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(_testStore.ConnectionString); - _options = optionsBuilder.Options; + _options = new DbContextOptionsBuilder() + .UseSqlite(_testStore.ConnectionString) + .UseInternalServiceProvider(_serviceProvider) + .Options; - using (var context = new DbContext(_serviceProvider, _options)) + using (var context = new DbContext(_options)) { context.Database.EnsureCreated(); @@ -39,7 +40,7 @@ public OneToOneQuerySqliteFixture() } } - public DbContext CreateContext() => new DbContext(_serviceProvider, _options); + public DbContext CreateContext() => new DbContext(_options); public void Dispose() => _testStore.Dispose(); } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/QueryNoClientEvalSqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/QueryNoClientEvalSqliteFixture.cs index ebf127a1b3d..39ba507fa93 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/QueryNoClientEvalSqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/QueryNoClientEvalSqliteFixture.cs @@ -7,7 +7,7 @@ namespace Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests { public class QueryNoClientEvalSqliteFixture : NorthwindQuerySqliteFixture { - protected override void ConfigureOptions(SqliteDbContextOptionsBuilder sqlServerDbContextOptionsBuilder) + protected override SqliteDbContextOptionsBuilder ConfigureOptions(SqliteDbContextOptionsBuilder sqlServerDbContextOptionsBuilder) => sqlServerDbContextOptionsBuilder.QueryClientEvaluationBehavior(QueryClientEvaluationBehavior.Throw); } } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/SqliteDatabaseCreatorTest.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/SqliteDatabaseCreatorTest.cs index 5789c840b69..5d12026a270 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/SqliteDatabaseCreatorTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/SqliteDatabaseCreatorTest.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; @@ -30,17 +31,13 @@ public void Exists_returns_true_when_database_exists() } private IRelationalDatabaseCreator GetDatabaseCreator(string connectionString) - { - var services = new ServiceCollection(); - services - .AddEntityFramework() - .AddSqlite(); - - var options = new DbContextOptionsBuilder(); - options.UseSqlite(connectionString); - - return new DbContext(services.BuildServiceProvider(), options.Options) + => new DbContext(new DbContextOptionsBuilder() + .UseSqlite(connectionString) + .UseInternalServiceProvider(new ServiceCollection() + .AddEntityFramework() + .AddSqlite() + .BuildServiceProvider()) + .Options) .GetService(); - } } } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/SqliteForeignKeyTest.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/SqliteForeignKeyTest.cs index c502bba10df..5c3d61cb37d 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/SqliteForeignKeyTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/SqliteForeignKeyTest.cs @@ -25,14 +25,15 @@ public SqliteForeignKeyTest() [InlineData(false)] public void It_enforces_foreign_key(bool suppress) { - var builder = new DbContextOptionsBuilder(); - var sqliteBuilder = builder.UseSqlite(_testStore.ConnectionString); - if (suppress) - { - sqliteBuilder.SuppressForeignKeyEnforcement(); - } - - var options = builder.Options; + var options = new DbContextOptionsBuilder() + .UseSqlite(_testStore.ConnectionString, + b => + { + if (suppress) + { + b.SuppressForeignKeyEnforcement(); + } + }).Options; using (var context = new MyContext(options)) { diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/StoreGeneratedSqliteTest.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/StoreGeneratedSqliteTest.cs index e5dbb7975fd..3fae05a9125 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/StoreGeneratedSqliteTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/StoreGeneratedSqliteTest.cs @@ -34,10 +34,11 @@ public override SqliteTestStore CreateTestStore() { return SqliteTestStore.GetOrCreateShared(DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(SqliteTestStore.CreateConnectionString(DatabaseName)); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(SqliteTestStore.CreateConnectionString(DatabaseName)) + .UseInternalServiceProvider(_serviceProvider); - using (var context = new StoreGeneratedContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new StoreGeneratedContext(optionsBuilder.Options)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); @@ -47,10 +48,11 @@ public override SqliteTestStore CreateTestStore() public override DbContext CreateContext(SqliteTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(testStore.Connection); + var optionsBuilder = new DbContextOptionsBuilder() + .UseSqlite(testStore.Connection) + .UseInternalServiceProvider(_serviceProvider); - var context = new StoreGeneratedContext(_serviceProvider, optionsBuilder.Options); + var context = new StoreGeneratedContext(optionsBuilder.Options); context.Database.UseTransaction(testStore.Transaction); return context; diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/TestModels/SqliteNorthwindContext.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/TestModels/SqliteNorthwindContext.cs index b6698488d5a..f95dd9fdf13 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/TestModels/SqliteNorthwindContext.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/TestModels/SqliteNorthwindContext.cs @@ -9,8 +9,8 @@ namespace Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests.TestModels { public class SqliteNorthwindContext : NorthwindContext { - public SqliteNorthwindContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public SqliteNorthwindContext(DbContextOptions options) + : base(options) { } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/TransactionSqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/TransactionSqliteFixture.cs index 738fc572cac..eec0b1b4b85 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/TransactionSqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/TransactionSqliteFixture.cs @@ -34,19 +34,13 @@ public override SqliteTestStore CreateTestStore() } public override DbContext CreateContext(SqliteTestStore testStore) - { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(testStore.ConnectionString); - - return new DbContext(_serviceProvider, optionsBuilder.Options); - } + => new DbContext(new DbContextOptionsBuilder() + .UseSqlite(testStore.ConnectionString) + .UseInternalServiceProvider(_serviceProvider).Options); public override DbContext CreateContext(DbConnection connection) - { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(connection); - - return new DbContext(_serviceProvider, optionsBuilder.Options); - } + => new DbContext(new DbContextOptionsBuilder() + .UseSqlite(connection) + .UseInternalServiceProvider(_serviceProvider).Options); } } diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/UpdatesSqliteFixture.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/UpdatesSqliteFixture.cs index 0bbf2ced0a7..1264476e420 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/UpdatesSqliteFixture.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.FunctionalTests/UpdatesSqliteFixture.cs @@ -29,10 +29,9 @@ public override SqliteTestStore CreateTestStore() => DatabaseName, () => { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(_connectionString); - - using (var context = new UpdatesContext(_serviceProvider, optionsBuilder.Options)) + using (var context = new UpdatesContext(new DbContextOptionsBuilder() + .UseSqlite(_connectionString) + .UseInternalServiceProvider(_serviceProvider).Options)) { // TODO: Delete DB if model changed context.Database.EnsureDeleted(); @@ -47,11 +46,10 @@ public override SqliteTestStore CreateTestStore() => public override UpdatesContext CreateContext(SqliteTestStore testStore) { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite(testStore.Connection) - .SuppressForeignKeyEnforcement(); - - var context = new UpdatesContext(_serviceProvider, optionsBuilder.Options); + var context = new UpdatesContext(new DbContextOptionsBuilder() + .UseSqlite(testStore.Connection, + b => b.SuppressForeignKeyEnforcement()) + .UseInternalServiceProvider(_serviceProvider).Options); context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; diff --git a/test/Microsoft.EntityFrameworkCore.Sqlite.Tests/SqliteDbContextOptionsBuilderExtensionsTest.cs b/test/Microsoft.EntityFrameworkCore.Sqlite.Tests/SqliteDbContextOptionsBuilderExtensionsTest.cs index 2c4d852e7f2..072bc3fe88b 100644 --- a/test/Microsoft.EntityFrameworkCore.Sqlite.Tests/SqliteDbContextOptionsBuilderExtensionsTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Sqlite.Tests/SqliteDbContextOptionsBuilderExtensionsTest.cs @@ -14,7 +14,7 @@ public class SqliteDbContextOptionsBuilderExtensionsTest public void Can_add_extension_with_max_batch_size() { var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite("Database=Crunchie").MaxBatchSize(123); + optionsBuilder.UseSqlite("Database=Crunchie", b => b.MaxBatchSize(123)); var extension = optionsBuilder.Options.Extensions.OfType().Single(); @@ -25,7 +25,7 @@ public void Can_add_extension_with_max_batch_size() public void Can_add_extension_with_command_timeout() { var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite("Database=Crunchie").CommandTimeout(30); + optionsBuilder.UseSqlite("Database=Crunchie", b => b.CommandTimeout(30)); var extension = optionsBuilder.Options.Extensions.OfType().Single(); @@ -36,7 +36,7 @@ public void Can_add_extension_with_command_timeout() public void Can_add_extension_with_ambient_transaction_warning_suppressed() { var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite("Database=Crunchie").SuppressAmbientTransactionWarning(); + optionsBuilder.UseSqlite("Database=Crunchie", b => b.SuppressAmbientTransactionWarning()); var extension = optionsBuilder.Options.Extensions.OfType().Single(); @@ -101,8 +101,7 @@ public void Can_suppress_foreign_keys() { var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseSqlite("some string") - .SuppressForeignKeyEnforcement(); + optionsBuilder.UseSqlite("some string", b => b.SuppressForeignKeyEnforcement()); var extension = optionsBuilder.Options.Extensions.OfType().Single(); diff --git a/test/Microsoft.EntityFrameworkCore.Tests/ChangeTracking/ChangeTrackerTest.cs b/test/Microsoft.EntityFrameworkCore.Tests/ChangeTracking/ChangeTrackerTest.cs index c533e6c493c..12b2370748e 100644 --- a/test/Microsoft.EntityFrameworkCore.Tests/ChangeTracking/ChangeTrackerTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Tests/ChangeTracking/ChangeTrackerTest.cs @@ -1035,14 +1035,16 @@ private class OrderDetails private class EarlyLearningCenter : DbContext { + private readonly IServiceProvider _serviceProvider; + public EarlyLearningCenter() - : this(TestHelpers.Instance.CreateServiceProvider()) { + _serviceProvider = TestHelpers.Instance.CreateServiceProvider(); } public EarlyLearningCenter(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } protected internal override void OnModelCreating(ModelBuilder modelBuilder) @@ -1071,7 +1073,9 @@ protected internal override void OnModelCreating(ModelBuilder modelBuilder) } protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseInMemoryDatabase(); + => optionsBuilder + .UseInternalServiceProvider(_serviceProvider) + .UseInMemoryDatabase(); } public class KeyValueEntityTracker diff --git a/test/Microsoft.EntityFrameworkCore.Tests/ChangeTracking/EntityEntryTest.cs b/test/Microsoft.EntityFrameworkCore.Tests/ChangeTracking/EntityEntryTest.cs index fec60febae8..8538b4852f8 100644 --- a/test/Microsoft.EntityFrameworkCore.Tests/ChangeTracking/EntityEntryTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Tests/ChangeTracking/EntityEntryTest.cs @@ -213,13 +213,10 @@ private class Chunky private class FreezerContext : DbContext { - public FreezerContext() - : base(TestHelpers.Instance.CreateServiceProvider()) - { - } - protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseInMemoryDatabase(); + => optionsBuilder + .UseInMemoryDatabase() + .UseInternalServiceProvider(TestHelpers.Instance.CreateServiceProvider()); public DbSet Icecream { get; set; } } diff --git a/test/Microsoft.EntityFrameworkCore.Tests/ContextConfigurationTest.cs b/test/Microsoft.EntityFrameworkCore.Tests/ContextConfigurationTest.cs index b2816640532..0fdedcf3132 100644 --- a/test/Microsoft.EntityFrameworkCore.Tests/ContextConfigurationTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Tests/ContextConfigurationTest.cs @@ -92,19 +92,21 @@ public void Scoped_provider_services_can_be_obtained_from_configuration_with_imp private class GiddyupContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public GiddyupContext() { } public GiddyupContext([NotNull] IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseInMemoryDatabase(); - } + => optionsBuilder + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); } } } diff --git a/test/Microsoft.EntityFrameworkCore.Tests/DbContextTest.cs b/test/Microsoft.EntityFrameworkCore.Tests/DbContextTest.cs index 0ee69e633a3..54eeae860a0 100644 --- a/test/Microsoft.EntityFrameworkCore.Tests/DbContextTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Tests/DbContextTest.cs @@ -34,9 +34,11 @@ public class DbContextTest public void Set_throws_for_type_not_in_model() { var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); + optionsBuilder + .UseInMemoryDatabase() + .UseInternalServiceProvider(TestHelpers.Instance.CreateServiceProvider()); - using (var context = new DbContext(TestHelpers.Instance.CreateServiceProvider(), optionsBuilder.Options)) + using (var context = new DbContext(optionsBuilder.Options)) { var ex = Assert.Throws(() => context.Set()); Assert.Equal(CoreStrings.InvalidSetType(nameof(Category)), ex.Message); @@ -65,13 +67,13 @@ public void Each_context_gets_new_scoped_services() public void Each_context_gets_new_scoped_services_with_implicit_services() { IServiceProvider contextServices; - using (var context = new Mock(null, null) { CallBase = true }.Object) + using (var context = new Mock { CallBase = true }.Object) { contextServices = ((IInfrastructure)context).Instance; Assert.Same(contextServices, ((IInfrastructure)context).Instance); } - using (var context = new Mock(null, null) { CallBase = true }.Object) + using (var context = new Mock { CallBase = true }.Object) { Assert.NotSame(contextServices, ((IInfrastructure)context).Instance); } @@ -82,16 +84,16 @@ public void Each_context_gets_new_scoped_services_with_explicit_config() { var serviceProvider = TestHelpers.Instance.CreateServiceProvider(); - var options = new DbContextOptionsBuilder().Options; + var options = new DbContextOptionsBuilder().UseInternalServiceProvider(serviceProvider).Options; IServiceProvider contextServices; - using (var context = new DbContext(serviceProvider, options)) + using (var context = new DbContext(options)) { contextServices = ((IInfrastructure)context).Instance; Assert.Same(contextServices, ((IInfrastructure)context).Instance); } - using (var context = new DbContext(serviceProvider, options)) + using (var context = new DbContext(options)) { Assert.NotSame(contextServices, ((IInfrastructure)context).Instance); } @@ -124,7 +126,7 @@ public void SaveChanges_calls_DetectChanges() var serviceProvider = TestHelpers.Instance.CreateServiceProvider(services); - using (var context = new DbContext(serviceProvider, new DbContextOptionsBuilder().Options)) + using (var context = new DbContext(new DbContextOptionsBuilder().UseInternalServiceProvider(serviceProvider).Options)) { var changeDetector = (FakeChangeDetector)context.GetService(); @@ -145,7 +147,8 @@ public void SaveChanges_calls_state_manager_SaveChanges() var serviceProvider = TestHelpers.Instance.CreateServiceProvider(services); - using (var context = new DbContext(serviceProvider, new DbContextOptionsBuilder().Options)) + using (var context = new DbContext( + new DbContextOptionsBuilder().UseInternalServiceProvider(serviceProvider).Options)) { var stateManager = (FakeStateManager)context.GetService(); @@ -170,7 +173,8 @@ public async Task SaveChangesAsync_calls_state_manager_SaveChangesAsync() var serviceProvider = TestHelpers.Instance.CreateServiceProvider(services); - using (var context = new DbContext(serviceProvider, new DbContextOptionsBuilder().Options)) + using (var context = new DbContext( + new DbContextOptionsBuilder().UseInternalServiceProvider(serviceProvider).Options)) { context.ChangeTracker.AutoDetectChangesEnabled = false; @@ -2113,26 +2117,31 @@ private class TheGu private class EarlyLearningCenter : DbContext { + private readonly IServiceProvider _serviceProvider; + public EarlyLearningCenter() { } public EarlyLearningCenter(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public EarlyLearningCenter(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + : base(options) { + _serviceProvider = serviceProvider; } public DbSet Products { get; set; } public DbSet Categories { get; set; } public DbSet Gus { get; set; } - protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseInMemoryDatabase(); + protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + => optionsBuilder + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); protected internal override void OnModelCreating(ModelBuilder modelBuilder) { @@ -2164,7 +2173,7 @@ public void Dispose() private class FakeModelSource : IModelSource { - public virtual IModel GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator = null) + public virtual IModel GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator = null) => null; } @@ -2193,10 +2202,10 @@ public void Can_use_derived_context() [Fact] public void Can_use_derived_context_with_external_services() { - var appServices = new ServiceCollection(); - appServices.AddLogging(); - appServices.AddCaching(); - var appServiceProivder = appServices.BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddLogging() + .AddCaching() + .BuildServiceProvider(); var loggerFactory = new WrappingLoggerFactory(appServiceProivder.GetService()); var memoryCache = appServiceProivder.GetService(); @@ -2224,9 +2233,9 @@ public void Can_use_derived_context_with_external_services() [Fact] public void Can_use_derived_context_with_options() { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - var options = optionsBuilder.Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .Options; var singleton = new object[3]; @@ -2252,21 +2261,23 @@ public void Can_use_derived_context_with_options() [Fact] public void Can_use_derived_context_with_options_and_external_services() { - var appServices = new ServiceCollection(); - appServices.AddLogging(); - appServices.AddCaching(); - var appServiceProivder = appServices.BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddLogging() + .AddCaching() + .BuildServiceProvider(); var loggerFactory = new WrappingLoggerFactory(appServiceProivder.GetService()); var memoryCache = appServiceProivder.GetService(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - var options = optionsBuilder.Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseLoggerFactory(loggerFactory) + .UseMemoryCache(memoryCache) + .Options; IInMemoryStore singleton; - using (var context = new ConstructorTestContextWithOC3B(options, loggerFactory, memoryCache)) + using (var context = new ConstructorTestContextWithOC3A(options)) { Assert.NotNull(singleton = context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2277,7 +2288,7 @@ public void Can_use_derived_context_with_options_and_external_services() Assert.Contains("System.Random", loggerFactory.CreatedLoggers); } - using (var context = new ConstructorTestContextWithOC3B(options, loggerFactory, memoryCache)) + using (var context = new ConstructorTestContextWithOC3A(options)) { Assert.Same(singleton, context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2289,9 +2300,10 @@ public void Can_use_derived_context_with_options_and_external_services() [Fact] public void Can_use_derived_context_controlling_internal_services() { - var internalServices = new ServiceCollection(); - internalServices.AddEntityFramework().AddInMemoryDatabase(); - var internalServiceProivder = internalServices.BuildServiceProvider(); + var internalServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .BuildServiceProvider(); var singleton = new object[3]; @@ -2319,14 +2331,15 @@ public void Can_use_derived_context_controlling_internal_services() [Fact] public void Can_use_derived_context_controlling_internal_services_with_external_services() { - var internalServices = new ServiceCollection(); - internalServices.AddEntityFramework().AddInMemoryDatabase(); - var internalServiceProivder = internalServices.BuildServiceProvider(); + var internalServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .BuildServiceProvider(); - var appServices = new ServiceCollection(); - appServices.AddLogging(); - appServices.AddCaching(); - var appServiceProivder = appServices.BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddLogging() + .AddCaching() + .BuildServiceProvider(); var loggerFactory = new WrappingLoggerFactory(appServiceProivder.GetService()); var memoryCache = appServiceProivder.GetService(); @@ -2356,17 +2369,19 @@ public void Can_use_derived_context_controlling_internal_services_with_external_ [Fact] public void Can_use_derived_context_controlling_internal_services_with_options() { - var internalServices = new ServiceCollection(); - internalServices.AddEntityFramework().AddInMemoryDatabase(); - var internalServiceProivder = internalServices.BuildServiceProvider(); + var internalServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - var options = optionsBuilder.Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(internalServiceProivder) + .Options; var singleton = new object[3]; - using (var context = new ConstructorTestContextWithOC4A(internalServiceProivder, options)) + using (var context = new ConstructorTestContextWithOC3A(options)) { Assert.NotNull(singleton[0] = context.GetService()); Assert.NotNull(singleton[1] = context.GetService()); @@ -2380,7 +2395,7 @@ public void Can_use_derived_context_controlling_internal_services_with_options() Assert.Same(singleton[2], internalServiceProivder.GetService()); } - using (var context = new ConstructorTestContextWithOC4A(internalServiceProivder, options)) + using (var context = new ConstructorTestContextWithOC3A(options)) { Assert.Same(singleton[0], context.GetService()); Assert.Same(singleton[1], context.GetService()); @@ -2392,25 +2407,29 @@ public void Can_use_derived_context_controlling_internal_services_with_options() [Fact] public void Can_use_derived_context_controlling_internal_services_with_options_and_external_services() { - var internalServices = new ServiceCollection(); - internalServices.AddEntityFramework().AddInMemoryDatabase(); - var internalServiceProivder = internalServices.BuildServiceProvider(); + var internalServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .BuildServiceProvider(); - var appServices = new ServiceCollection(); - appServices.AddLogging(); - appServices.AddCaching(); - var appServiceProivder = appServices.BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddLogging() + .AddCaching() + .BuildServiceProvider(); var loggerFactory = new WrappingLoggerFactory(appServiceProivder.GetService()); var memoryCache = appServiceProivder.GetService(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - var options = optionsBuilder.Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseLoggerFactory(loggerFactory) + .UseMemoryCache(memoryCache) + .UseInternalServiceProvider(internalServiceProivder) + .Options; IInMemoryStore singleton; - using (var context = new ConstructorTestContextWithOC4B(internalServiceProivder, options, loggerFactory, memoryCache)) + using (var context = new ConstructorTestContextWithOC3A(options)) { Assert.NotNull(singleton = context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2423,7 +2442,7 @@ public void Can_use_derived_context_controlling_internal_services_with_options_a Assert.Same(singleton, internalServiceProivder.GetService()); } - using (var context = new ConstructorTestContextWithOC4B(internalServiceProivder, options, loggerFactory, memoryCache)) + using (var context = new ConstructorTestContextWithOC3A(options)) { Assert.Same(singleton, context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2435,9 +2454,9 @@ public void Can_use_derived_context_controlling_internal_services_with_options_a [Fact] public void Can_use_derived_context_with_options_no_OnConfiguring() { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - var options = optionsBuilder.Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .Options; var singleton = new object[3]; @@ -2463,21 +2482,23 @@ public void Can_use_derived_context_with_options_no_OnConfiguring() [Fact] public void Can_use_derived_context_with_options_and_external_services_no_OnConfiguring() { - var appServices = new ServiceCollection(); - appServices.AddLogging(); - appServices.AddCaching(); - var appServiceProivder = appServices.BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddLogging() + .AddCaching() + .BuildServiceProvider(); var loggerFactory = new WrappingLoggerFactory(appServiceProivder.GetService()); var memoryCache = appServiceProivder.GetService(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - var options = optionsBuilder.Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseLoggerFactory(loggerFactory) + .UseMemoryCache(memoryCache) + .Options; IInMemoryStore singleton; - using (var context = new ConstructorTestContext1B(options, loggerFactory, memoryCache)) + using (var context = new ConstructorTestContext1A(options)) { Assert.NotNull(singleton = context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2488,7 +2509,7 @@ public void Can_use_derived_context_with_options_and_external_services_no_OnConf Assert.Contains("System.Random", loggerFactory.CreatedLoggers); } - using (var context = new ConstructorTestContext1B(options, loggerFactory, memoryCache)) + using (var context = new ConstructorTestContext1A(options)) { Assert.Same(singleton, context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2500,17 +2521,19 @@ public void Can_use_derived_context_with_options_and_external_services_no_OnConf [Fact] public void Can_use_derived_context_controlling_internal_services_with_options_no_OnConfiguring() { - var internalServices = new ServiceCollection(); - internalServices.AddEntityFramework().AddInMemoryDatabase(); - var internalServiceProivder = internalServices.BuildServiceProvider(); + var internalServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - var options = optionsBuilder.Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(internalServiceProivder) + .Options; var singleton = new object[3]; - using (var context = new ConstructorTestContext2A(internalServiceProivder, options)) + using (var context = new ConstructorTestContext1A(options)) { Assert.NotNull(singleton[0] = context.GetService()); Assert.NotNull(singleton[1] = context.GetService()); @@ -2524,7 +2547,7 @@ public void Can_use_derived_context_controlling_internal_services_with_options_n Assert.Same(singleton[2], internalServiceProivder.GetService()); } - using (var context = new ConstructorTestContext2A(internalServiceProivder, options)) + using (var context = new ConstructorTestContext1A(options)) { Assert.Same(singleton[0], context.GetService()); Assert.Same(singleton[1], context.GetService()); @@ -2536,25 +2559,29 @@ public void Can_use_derived_context_controlling_internal_services_with_options_n [Fact] public void Can_use_derived_context_controlling_internal_services_with_options_and_external_services_no_OnConfiguring() { - var internalServices = new ServiceCollection(); - internalServices.AddEntityFramework().AddInMemoryDatabase(); - var internalServiceProivder = internalServices.BuildServiceProvider(); + var internalServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .BuildServiceProvider(); - var appServices = new ServiceCollection(); - appServices.AddLogging(); - appServices.AddCaching(); - var appServiceProivder = appServices.BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddLogging() + .AddCaching() + .BuildServiceProvider(); var loggerFactory = new WrappingLoggerFactory(appServiceProivder.GetService()); var memoryCache = appServiceProivder.GetService(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - var options = optionsBuilder.Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseLoggerFactory(loggerFactory) + .UseMemoryCache(memoryCache) + .UseInternalServiceProvider(internalServiceProivder) + .Options; IInMemoryStore singleton; - using (var context = new ConstructorTestContext2B(internalServiceProivder, options, loggerFactory, memoryCache)) + using (var context = new ConstructorTestContext1A(options)) { Assert.NotNull(singleton = context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2567,7 +2594,7 @@ public void Can_use_derived_context_controlling_internal_services_with_options_a Assert.Same(singleton, internalServiceProivder.GetService()); } - using (var context = new ConstructorTestContext2B(internalServiceProivder, options, loggerFactory, memoryCache)) + using (var context = new ConstructorTestContext1A(options)) { Assert.Same(singleton, context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2579,9 +2606,9 @@ public void Can_use_derived_context_controlling_internal_services_with_options_a [Fact] public void Can_use_non_derived_context_with_options() { - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - var options = optionsBuilder.Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .Options; var singleton = new object[3]; @@ -2607,21 +2634,23 @@ public void Can_use_non_derived_context_with_options() [Fact] public void Can_use_non_derived_context_with_options_and_external_services() { - var appServices = new ServiceCollection(); - appServices.AddLogging(); - appServices.AddCaching(); - var appServiceProivder = appServices.BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddLogging() + .AddCaching() + .BuildServiceProvider(); var loggerFactory = new WrappingLoggerFactory(appServiceProivder.GetService()); var memoryCache = appServiceProivder.GetService(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - var options = optionsBuilder.Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseLoggerFactory(loggerFactory) + .UseMemoryCache(memoryCache) + .Options; IInMemoryStore singleton; - using (var context = new DbContext(options, loggerFactory, memoryCache)) + using (var context = new DbContext(options)) { Assert.NotNull(singleton = context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2632,7 +2661,7 @@ public void Can_use_non_derived_context_with_options_and_external_services() Assert.Contains("System.Random", loggerFactory.CreatedLoggers); } - using (var context = new DbContext(options, loggerFactory, memoryCache)) + using (var context = new DbContext(options)) { Assert.Same(singleton, context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2644,17 +2673,19 @@ public void Can_use_non_derived_context_with_options_and_external_services() [Fact] public void Can_use_non_derived_context_controlling_internal_services_with_options() { - var internalServices = new ServiceCollection(); - internalServices.AddEntityFramework().AddInMemoryDatabase(); - var internalServiceProivder = internalServices.BuildServiceProvider(); + var internalServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .BuildServiceProvider(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - var options = optionsBuilder.Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseInternalServiceProvider(internalServiceProivder) + .Options; var singleton = new object[3]; - using (var context = new DbContext(internalServiceProivder, options)) + using (var context = new DbContext(options)) { Assert.NotNull(singleton[0] = context.GetService()); Assert.NotNull(singleton[1] = context.GetService()); @@ -2668,7 +2699,7 @@ public void Can_use_non_derived_context_controlling_internal_services_with_optio Assert.Same(singleton[2], internalServiceProivder.GetService()); } - using (var context = new DbContext(internalServiceProivder, options)) + using (var context = new DbContext(options)) { Assert.Same(singleton[0], context.GetService()); Assert.Same(singleton[1], context.GetService()); @@ -2680,25 +2711,29 @@ public void Can_use_non_derived_context_controlling_internal_services_with_optio [Fact] public void Can_use_non_derived_context_controlling_internal_services_with_options_and_external_services() { - var internalServices = new ServiceCollection(); - internalServices.AddEntityFramework().AddInMemoryDatabase(); - var internalServiceProivder = internalServices.BuildServiceProvider(); + var internalServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .BuildServiceProvider(); - var appServices = new ServiceCollection(); - appServices.AddLogging(); - appServices.AddCaching(); - var appServiceProivder = appServices.BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddLogging() + .AddCaching() + .BuildServiceProvider(); var loggerFactory = new WrappingLoggerFactory(appServiceProivder.GetService()); var memoryCache = appServiceProivder.GetService(); - var optionsBuilder = new DbContextOptionsBuilder(); - optionsBuilder.UseInMemoryDatabase(); - var options = optionsBuilder.Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase() + .UseLoggerFactory(loggerFactory) + .UseMemoryCache(memoryCache) + .UseInternalServiceProvider(internalServiceProivder) + .Options; IInMemoryStore singleton; - using (var context = new DbContext(internalServiceProivder, options, loggerFactory, memoryCache)) + using (var context = new DbContext(options)) { Assert.NotNull(singleton = context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2711,7 +2746,7 @@ public void Can_use_non_derived_context_controlling_internal_services_with_optio Assert.Same(singleton, internalServiceProivder.GetService()); } - using (var context = new DbContext(internalServiceProivder, options, loggerFactory, memoryCache)) + using (var context = new DbContext(options)) { Assert.Same(singleton, context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2723,10 +2758,9 @@ public void Can_use_non_derived_context_controlling_internal_services_with_optio [Fact] public void Can_add_derived_context() { - var appServiceProivder - = new ServiceCollection() - .AddDbContext() - .BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddDbContext() + .BuildServiceProvider(); var singleton = new object[3]; DbContext context1; @@ -2765,10 +2799,9 @@ var appServiceProivder [Fact] public void Can_add_derived_context_with_external_services() { - var appServiceProivder - = new ServiceCollection() - .AddDbContext() - .BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddDbContext() + .BuildServiceProvider(); var loggerFactory = appServiceProivder.GetService(); var memoryCache = appServiceProivder.GetService(); @@ -2803,10 +2836,9 @@ var appServiceProivder [Fact] public void Can_add_derived_context_with_options() { - var appServiceProivder - = new ServiceCollection() - .AddDbContext(b => b.UseInMemoryDatabase()) - .BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddDbContext(b => b.UseInMemoryDatabase()) + .BuildServiceProvider(); var singleton = new object[4]; @@ -2840,10 +2872,9 @@ var appServiceProivder [Fact] public void Can_add_derived_context_with_options_and_external_services() { - var appServiceProivder - = new ServiceCollection() - .AddDbContext(b => b.UseInMemoryDatabase()) - .BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddDbContext(b => b.UseInMemoryDatabase()) + .BuildServiceProvider(); var loggerFactory = appServiceProivder.GetService(); var memoryCache = appServiceProivder.GetService(); @@ -2855,7 +2886,7 @@ var appServiceProivder .GetRequiredService() .CreateScope()) { - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService(); Assert.NotNull(singleton = context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2869,7 +2900,7 @@ var appServiceProivder .GetRequiredService() .CreateScope()) { - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService(); Assert.Same(singleton, context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -2881,12 +2912,11 @@ var appServiceProivder [Fact] public void Can_add_derived_context_controlling_internal_services() { - var appServiceProivder - = new ServiceCollection() - .AddEntityFramework() - .AddInMemoryDatabase() - .AddDbContext() - .BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .AddDbContext() + .BuildServiceProvider(); var singleton = new object[3]; @@ -2918,12 +2948,11 @@ var appServiceProivder [Fact] public void Can_add_derived_context_controlling_internal_services_with_external_services() { - var appServiceProivder - = new ServiceCollection() - .AddEntityFramework() - .AddInMemoryDatabase() - .AddDbContext() - .BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .AddDbContext() + .BuildServiceProvider(); var loggerFactory = appServiceProivder.GetService(); var memoryCache = appServiceProivder.GetService(); @@ -2958,12 +2987,16 @@ var appServiceProivder [Fact] public void Can_add_derived_context_controlling_internal_services_with_options() { - var appServiceProivder - = new ServiceCollection() - .AddEntityFramework() - .AddInMemoryDatabase() - .AddDbContext(b => b.UseInMemoryDatabase()) - .BuildServiceProvider(); + var internalServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .BuildServiceProvider(); + + var appServiceProivder = new ServiceCollection() + .AddDbContext( + b => b.UseInMemoryDatabase() + .UseInternalServiceProvider(internalServiceProivder)) + .BuildServiceProvider(); var singleton = new object[4]; @@ -2971,7 +3004,7 @@ var appServiceProivder .GetRequiredService() .CreateScope()) { - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService(); Assert.NotNull(singleton[0] = context.GetService()); Assert.NotNull(singleton[1] = context.GetService()); @@ -2985,7 +3018,7 @@ var appServiceProivder .GetRequiredService() .CreateScope()) { - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService(); Assert.Same(singleton[0], context.GetService()); Assert.Same(singleton[1], context.GetService()); @@ -2997,12 +3030,16 @@ var appServiceProivder [Fact] public void Can_add_derived_context_controlling_internal_services_with_options_and_external_services() { - var appServiceProivder - = new ServiceCollection() - .AddEntityFramework() - .AddInMemoryDatabase() - .AddDbContext(b => b.UseInMemoryDatabase()) - .BuildServiceProvider(); + var internalServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .BuildServiceProvider(); + + var appServiceProivder = new ServiceCollection() + .AddDbContext( + b => b.UseInMemoryDatabase() + .UseInternalServiceProvider(internalServiceProivder)) + .BuildServiceProvider(); var loggerFactory = appServiceProivder.GetService(); var memoryCache = appServiceProivder.GetService(); @@ -3014,7 +3051,7 @@ var appServiceProivder .GetRequiredService() .CreateScope()) { - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService(); Assert.NotNull(singleton = context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -3028,7 +3065,89 @@ var appServiceProivder .GetRequiredService() .CreateScope()) { - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService(); + + Assert.Same(singleton, context.GetService()); + Assert.Same(loggerFactory, context.GetService().LoggerFactory); + Assert.Same(memoryCache, context.GetService().MemoryCache); + Assert.Same(options, context.GetService()); + } + } + + [Fact] + public void Can_add_derived_context_one_service_provider_with_options() + { + var appServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .AddDbContext( + (p, b) => b.UseInMemoryDatabase().UseInternalServiceProvider(p)) + .BuildServiceProvider(); + + var singleton = new object[4]; + + using (var serviceScope = appServiceProivder + .GetRequiredService() + .CreateScope()) + { + var context = serviceScope.ServiceProvider.GetService(); + + Assert.NotNull(singleton[0] = context.GetService()); + Assert.NotNull(singleton[1] = context.GetService()); + Assert.NotNull(singleton[2] = context.GetService()); + Assert.NotNull(singleton[3] = context.GetService()); + + Assert.NotNull(context.GetService>()); + } + + using (var serviceScope = appServiceProivder + .GetRequiredService() + .CreateScope()) + { + var context = serviceScope.ServiceProvider.GetService(); + + Assert.Same(singleton[0], context.GetService()); + Assert.Same(singleton[1], context.GetService()); + Assert.Same(singleton[2], context.GetService()); + Assert.Same(singleton[3], context.GetService()); + } + } + + [Fact] + public void Can_add_derived_context_one_service_provider_with_options_and_external_services() + { + var appServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .AddDbContext( + (p, b) => b.UseInMemoryDatabase().UseInternalServiceProvider(p)) + .BuildServiceProvider(); + + var loggerFactory = appServiceProivder.GetService(); + var memoryCache = appServiceProivder.GetService(); + + IInMemoryStore singleton; + IDbContextOptions options; + + using (var serviceScope = appServiceProivder + .GetRequiredService() + .CreateScope()) + { + var context = serviceScope.ServiceProvider.GetService(); + + Assert.NotNull(singleton = context.GetService()); + Assert.Same(loggerFactory, context.GetService().LoggerFactory); + Assert.Same(memoryCache, context.GetService().MemoryCache); + Assert.NotNull(options = context.GetService()); + + Assert.NotNull(context.GetService>()); + } + + using (var serviceScope = appServiceProivder + .GetRequiredService() + .CreateScope()) + { + var context = serviceScope.ServiceProvider.GetService(); Assert.Same(singleton, context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -3040,10 +3159,9 @@ var appServiceProivder [Fact] public void Can_add_derived_context_with_options_no_OnConfiguring() { - var appServiceProivder - = new ServiceCollection() - .AddDbContext(b => b.UseInMemoryDatabase()) - .BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddDbContext(b => b.UseInMemoryDatabase()) + .BuildServiceProvider(); var singleton = new object[4]; @@ -3077,10 +3195,9 @@ var appServiceProivder [Fact] public void Can_add_derived_context_with_options_and_external_services_no_OnConfiguring() { - var appServiceProivder - = new ServiceCollection() - .AddDbContext(b => b.UseInMemoryDatabase()) - .BuildServiceProvider(); + var appServiceProivder = new ServiceCollection() + .AddDbContext(b => b.UseInMemoryDatabase()) + .BuildServiceProvider(); var loggerFactory = appServiceProivder.GetService(); var memoryCache = appServiceProivder.GetService(); @@ -3092,7 +3209,7 @@ var appServiceProivder .GetRequiredService() .CreateScope()) { - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService(); Assert.NotNull(singleton = context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -3106,7 +3223,7 @@ var appServiceProivder .GetRequiredService() .CreateScope()) { - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService(); Assert.Same(singleton, context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -3118,12 +3235,16 @@ var appServiceProivder [Fact] public void Can_add_derived_context_controlling_internal_services_with_options_no_OnConfiguring() { - var appServiceProivder - = new ServiceCollection() - .AddEntityFramework() - .AddInMemoryDatabase() - .AddDbContext(b => b.UseInMemoryDatabase()) - .BuildServiceProvider(); + var internalServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .BuildServiceProvider(); + + var appServiceProivder = new ServiceCollection() + .AddDbContext( + b => b.UseInMemoryDatabase() + .UseInternalServiceProvider(internalServiceProivder)) + .BuildServiceProvider(); var singleton = new object[4]; @@ -3131,7 +3252,7 @@ var appServiceProivder .GetRequiredService() .CreateScope()) { - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService(); Assert.NotNull(singleton[0] = context.GetService()); Assert.NotNull(singleton[1] = context.GetService()); @@ -3145,7 +3266,7 @@ var appServiceProivder .GetRequiredService() .CreateScope()) { - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService(); Assert.Same(singleton[0], context.GetService()); Assert.Same(singleton[1], context.GetService()); @@ -3157,12 +3278,98 @@ var appServiceProivder [Fact] public void Can_add_derived_context_controlling_internal_services_with_options_and_external_services_no_OnConfiguring() { - var appServiceProivder - = new ServiceCollection() - .AddEntityFramework() - .AddInMemoryDatabase() - .AddDbContext(b => b.UseInMemoryDatabase()) - .BuildServiceProvider(); + var internalServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .BuildServiceProvider(); + + var appServiceProivder = new ServiceCollection() + .AddDbContext( + b => b.UseInMemoryDatabase() + .UseInternalServiceProvider(internalServiceProivder)) + .BuildServiceProvider(); + + var loggerFactory = appServiceProivder.GetService(); + var memoryCache = appServiceProivder.GetService(); + + IInMemoryStore singleton; + IDbContextOptions options; + + using (var serviceScope = appServiceProivder + .GetRequiredService() + .CreateScope()) + { + var context = serviceScope.ServiceProvider.GetService(); + + Assert.NotNull(singleton = context.GetService()); + Assert.Same(loggerFactory, context.GetService().LoggerFactory); + Assert.Same(memoryCache, context.GetService().MemoryCache); + Assert.NotNull(options = context.GetService()); + + Assert.NotNull(context.GetService>()); + } + + using (var serviceScope = appServiceProivder + .GetRequiredService() + .CreateScope()) + { + var context = serviceScope.ServiceProvider.GetService(); + + Assert.Same(singleton, context.GetService()); + Assert.Same(loggerFactory, context.GetService().LoggerFactory); + Assert.Same(memoryCache, context.GetService().MemoryCache); + Assert.Same(options, context.GetService()); + } + } + + [Fact] + public void Can_add_derived_context_one_provider_with_options_no_OnConfiguring() + { + var appServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .AddDbContext( + (p, b) => b.UseInMemoryDatabase().UseInternalServiceProvider(p)) + .BuildServiceProvider(); + + var singleton = new object[4]; + + using (var serviceScope = appServiceProivder + .GetRequiredService() + .CreateScope()) + { + var context = serviceScope.ServiceProvider.GetService(); + + Assert.NotNull(singleton[0] = context.GetService()); + Assert.NotNull(singleton[1] = context.GetService()); + Assert.NotNull(singleton[2] = context.GetService()); + Assert.NotNull(singleton[3] = context.GetService()); + + Assert.NotNull(context.GetService>()); + } + + using (var serviceScope = appServiceProivder + .GetRequiredService() + .CreateScope()) + { + var context = serviceScope.ServiceProvider.GetService(); + + Assert.Same(singleton[0], context.GetService()); + Assert.Same(singleton[1], context.GetService()); + Assert.Same(singleton[2], context.GetService()); + Assert.Same(singleton[3], context.GetService()); + } + } + + [Fact] + public void Can_add_derived_context_one_provider_with_options_and_external_services_no_OnConfiguring() + { + var appServiceProivder = new ServiceCollection() + .AddEntityFramework() + .AddInMemoryDatabase() + .AddDbContext( + (p, b) => b.UseInMemoryDatabase().UseInternalServiceProvider(p)) + .BuildServiceProvider(); var loggerFactory = appServiceProivder.GetService(); var memoryCache = appServiceProivder.GetService(); @@ -3174,7 +3381,7 @@ var appServiceProivder .GetRequiredService() .CreateScope()) { - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService(); Assert.NotNull(singleton = context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -3188,7 +3395,7 @@ var appServiceProivder .GetRequiredService() .CreateScope()) { - var context = serviceScope.ServiceProvider.GetService(); + var context = serviceScope.ServiceProvider.GetService(); Assert.Same(singleton, context.GetService()); Assert.Same(loggerFactory, context.GetService().LoggerFactory); @@ -3229,64 +3436,39 @@ public ConstructorTestContext1A( } } - private class ConstructorTestContext1B : DbContext - { - public ConstructorTestContext1B( - DbContextOptions options, - ILoggerFactory loggerFactory, - IMemoryCache memoryCache) - : base(options, loggerFactory, memoryCache) - { - } - } - - private class ConstructorTestContext2A : DbContext - { - public ConstructorTestContext2A( - IServiceProvider internalServicesProvider, - DbContextOptions options) - : base(internalServicesProvider, options) - { - } - } - - private class ConstructorTestContext2B : DbContext - { - public ConstructorTestContext2B( - IServiceProvider internalServicesProvider, - DbContextOptions options, - ILoggerFactory loggerFactory, - IMemoryCache memoryCache) - : base(internalServicesProvider, options, loggerFactory, memoryCache) - { - } - } - private class ConstructorTestContextWithOCBase : DbContext { + private readonly IServiceProvider _internalServicesProvider; + private readonly ILoggerFactory _loggerFactory; + private readonly IMemoryCache _memoryCache; private readonly bool _isConfigured; protected ConstructorTestContextWithOCBase( ILoggerFactory loggerFactory = null, IMemoryCache memoryCache = null) - : base(loggerFactory, memoryCache) { + _loggerFactory = loggerFactory; + _memoryCache = memoryCache; } protected ConstructorTestContextWithOCBase( IServiceProvider internalServicesProvider, ILoggerFactory loggerFactory = null, IMemoryCache memoryCache = null) - : base(internalServicesProvider, loggerFactory, memoryCache) { + _internalServicesProvider = internalServicesProvider; + _loggerFactory = loggerFactory; + _memoryCache = memoryCache; } protected ConstructorTestContextWithOCBase( DbContextOptions options, ILoggerFactory loggerFactory = null, IMemoryCache memoryCache = null) - : base(options, loggerFactory, memoryCache) + : base(options) { + _loggerFactory = loggerFactory; + _memoryCache = memoryCache; _isConfigured = true; } @@ -3295,8 +3477,11 @@ protected ConstructorTestContextWithOCBase( DbContextOptions options, ILoggerFactory loggerFactory = null, IMemoryCache memoryCache = null) - : base(internalServicesProvider, options, loggerFactory, memoryCache) + : base(options) { + _internalServicesProvider = internalServicesProvider; + _loggerFactory = loggerFactory; + _memoryCache = memoryCache; _isConfigured = true; } @@ -3308,6 +3493,21 @@ protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBu { optionsBuilder.UseInMemoryDatabase(); } + + if (_internalServicesProvider != null) + { + optionsBuilder.UseInternalServiceProvider(_internalServicesProvider); + } + + if (_memoryCache != null) + { + optionsBuilder.UseMemoryCache(_memoryCache); + } + + if (_loggerFactory != null) + { + optionsBuilder.UseLoggerFactory(_loggerFactory); + } } } @@ -3333,16 +3533,6 @@ public ConstructorTestContextWithOC3A( } } - private class ConstructorTestContextWithOC4A : ConstructorTestContextWithOCBase - { - public ConstructorTestContextWithOC4A( - IServiceProvider internalServicesProvider, - DbContextOptions options) - : base(internalServicesProvider, options) - { - } - } - private class ConstructorTestContextWithOC1B : ConstructorTestContextWithOCBase { public ConstructorTestContextWithOC1B( @@ -3364,29 +3554,6 @@ public ConstructorTestContextWithOC2B( } } - private class ConstructorTestContextWithOC3B : ConstructorTestContextWithOCBase - { - public ConstructorTestContextWithOC3B( - DbContextOptions options, - ILoggerFactory loggerFactory, - IMemoryCache memoryCache) - : base(options, loggerFactory, memoryCache) - { - } - } - - private class ConstructorTestContextWithOC4B : ConstructorTestContextWithOCBase - { - public ConstructorTestContextWithOC4B( - IServiceProvider internalServicesProvider, - DbContextOptions options, - ILoggerFactory loggerFactory, - IMemoryCache memoryCache) - : base(internalServicesProvider, options, loggerFactory, memoryCache) - { - } - } - [Fact] public void Model_cannot_be_used_in_OnModelCreating() { @@ -3405,9 +3572,11 @@ public void Model_cannot_be_used_in_OnModelCreating() private class UseModelInOnModelCreatingContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public UseModelInOnModelCreatingContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Products { get; set; } @@ -3418,7 +3587,9 @@ protected internal override void OnModelCreating(ModelBuilder modelBuilder) } protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseInMemoryDatabase(); + => optionsBuilder + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); } [Fact] @@ -3439,9 +3610,11 @@ public void Context_cannot_be_used_in_OnModelCreating() private class UseInOnModelCreatingContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public UseInOnModelCreatingContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Products { get; set; } @@ -3450,7 +3623,9 @@ protected internal override void OnModelCreating(ModelBuilder modelBuilder) => Products.ToList(); protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - => optionsBuilder.UseInMemoryDatabase(); + => optionsBuilder + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); } [Fact] @@ -3471,15 +3646,19 @@ public void Context_cannot_be_used_in_OnConfiguring() private class UseInOnConfiguringContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public UseInOnConfiguringContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Products { get; set; } protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { + optionsBuilder.UseInternalServiceProvider(_serviceProvider); + Products.ToList(); base.OnConfiguring(optionsBuilder); @@ -3569,17 +3748,19 @@ public async Task Auto_DetectChanges_for_SaveChanges_can_be_switched_off(bool as private class ButTheHedgehogContext : DbContext { + private readonly IServiceProvider _serviceProvider; + public ButTheHedgehogContext(IServiceProvider serviceProvider) - : base(serviceProvider) { + _serviceProvider = serviceProvider; } public DbSet Products { get; set; } protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseInMemoryDatabase(); - } + => optionsBuilder + .UseInMemoryDatabase() + .UseInternalServiceProvider(_serviceProvider); } [Theory] @@ -3769,7 +3950,8 @@ public void It_throws_with_derived_name() public void It_disposes_scope() { var fakeServiceProvider = new FakeServiceProvider(); - var context = new DbContext(fakeServiceProvider, new DbContextOptions()); + var context = new DbContext( + new DbContextOptionsBuilder().UseInternalServiceProvider(fakeServiceProvider).Options); var scopeService = Assert.IsType(context.GetService().CreateScope()); diff --git a/test/Microsoft.EntityFrameworkCore.Tests/DbSetInitializerTest.cs b/test/Microsoft.EntityFrameworkCore.Tests/DbSetInitializerTest.cs index 704fe7bd105..26a6bacdb65 100644 --- a/test/Microsoft.EntityFrameworkCore.Tests/DbSetInitializerTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Tests/DbSetInitializerTest.cs @@ -34,7 +34,8 @@ public void Initializes_all_entity_set_properties_with_setters() var serviceProvider = TestHelpers.Instance.CreateServiceProvider(customServices); - using (var context = new JustAContext(serviceProvider, new DbContextOptionsBuilder().Options)) + using (var context = new JustAContext( + new DbContextOptionsBuilder().UseInternalServiceProvider(serviceProvider).Options)) { Assert.NotNull(context.One); Assert.NotNull(context.GetTwo()); @@ -45,8 +46,8 @@ public void Initializes_all_entity_set_properties_with_setters() public class JustAContext : DbContext { - public JustAContext(IServiceProvider serviceProvider, DbContextOptions options) - : base(serviceProvider, options) + public JustAContext(DbContextOptions options) + : base(options) { } @@ -54,15 +55,9 @@ public JustAContext(IServiceProvider serviceProvider, DbContextOptions options) private DbSet Two { get; set; } public DbSet Three { get; private set; } - public DbSet Four - { - get { return null; } - } + public DbSet Four => null; - public DbSet GetTwo() - { - return Two; - } + public DbSet GetTwo() => Two; } } } diff --git a/test/Microsoft.EntityFrameworkCore.Tests/DbSetSourceTest.cs b/test/Microsoft.EntityFrameworkCore.Tests/DbSetSourceTest.cs index 4c82a8eccb4..9b04af76e00 100644 --- a/test/Microsoft.EntityFrameworkCore.Tests/DbSetSourceTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Tests/DbSetSourceTest.cs @@ -13,7 +13,7 @@ public class DbSetSourceTest [Fact] public void Can_create_new_generic_DbSet() { - var context = new Mock(null, null).Object; + var context = new Mock().Object; var factorySource = new DbSetSource(); @@ -25,7 +25,7 @@ public void Can_create_new_generic_DbSet() [Fact] public void Always_creates_a_new_DbSet_instance() { - var context = new Mock(null, null).Object; + var context = new Mock().Object; var factorySource = new DbSetSource(); diff --git a/test/Microsoft.EntityFrameworkCore.Tests/DbSetTest.cs b/test/Microsoft.EntityFrameworkCore.Tests/DbSetTest.cs index dc1480e75be..cbd63463010 100644 --- a/test/Microsoft.EntityFrameworkCore.Tests/DbSetTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Tests/DbSetTest.cs @@ -384,19 +384,14 @@ private class TheGu private class EarlyLearningCenter : DbContext { - public EarlyLearningCenter() - : base(TestHelpers.Instance.CreateServiceProvider()) - { - } - public DbSet Products { get; set; } public DbSet Categories { get; set; } public DbSet Gus { get; set; } protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - optionsBuilder.UseInMemoryDatabase(); - } + => optionsBuilder + .UseInMemoryDatabase() + .UseInternalServiceProvider(TestHelpers.Instance.CreateServiceProvider()); } } } diff --git a/test/Microsoft.EntityFrameworkCore.Tests/ModelSourceTest.cs b/test/Microsoft.EntityFrameworkCore.Tests/ModelSourceTest.cs index 3d68322e4cc..abe6ca4459a 100644 --- a/test/Microsoft.EntityFrameworkCore.Tests/ModelSourceTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Tests/ModelSourceTest.cs @@ -29,7 +29,7 @@ public void Adds_all_entities_based_on_all_distinct_entity_types_found() }); var model = CreateDefaultModelSource(setFinderMock.Object) - .GetModel(new Mock(null, null).Object, null, + .GetModel(new Mock().Object, null, new LoggingModelValidator(new Logger(new LoggerFactory()))); Assert.Equal( diff --git a/test/Microsoft.EntityFrameworkCore.Tests/Storage/DatabaseProviderSelectorTest.cs b/test/Microsoft.EntityFrameworkCore.Tests/Storage/DatabaseProviderSelectorTest.cs index 4d5d8aa3ebd..1b1259bbe35 100644 --- a/test/Microsoft.EntityFrameworkCore.Tests/Storage/DatabaseProviderSelectorTest.cs +++ b/test/Microsoft.EntityFrameworkCore.Tests/Storage/DatabaseProviderSelectorTest.cs @@ -23,7 +23,7 @@ public void Selects_single_configured_provider() Mock.Of(), new[] { provider }); - Assert.Same(provider.GetProviderServices(serviceProvider), selector.SelectServices(ServiceProviderSource.Explicit)); + Assert.Same(provider.GetProviderServices(serviceProvider), selector.SelectServices()); } [Fact] @@ -41,7 +41,7 @@ public void Throws_if_multiple_providers_configured() Assert.Equal(CoreStrings.MultipleProvidersConfigured("'Database1' 'Database2' 'Database4' "), Assert.Throws( - () => selector.SelectServices(ServiceProviderSource.Explicit)).Message); + () => selector.SelectServices()).Message); } [Fact] @@ -52,9 +52,9 @@ public void Throws_if_no_provider_services_have_been_registered_using_external_s Mock.Of(), null); - Assert.Equal(CoreStrings.NoProviderServices, + Assert.Equal(CoreStrings.NoProviderConfigured, Assert.Throws( - () => selector.SelectServices(ServiceProviderSource.Explicit)).Message); + () => selector.SelectServices()).Message); } [Fact] @@ -67,7 +67,7 @@ public void Throws_if_no_provider_services_have_been_registered_using_implicit_s Assert.Equal(CoreStrings.NoProviderConfigured, Assert.Throws( - () => selector.SelectServices(ServiceProviderSource.Implicit)).Message); + () => selector.SelectServices()).Message); } [Fact] @@ -84,7 +84,7 @@ public void Throws_if_multiple_provider_services_are_registered_but_none_are_con Assert.Equal(CoreStrings.MultipleProvidersAvailable("'Database1' 'Database2' 'Database3' "), Assert.Throws( - () => selector.SelectServices(ServiceProviderSource.Explicit)).Message); + () => selector.SelectServices()).Message); } [Fact] @@ -99,7 +99,7 @@ public void Throws_if_one_provider_service_is_registered_but_not_configured_and_ Assert.Equal(CoreStrings.NoProviderConfigured, Assert.Throws( - () => selector.SelectServices(ServiceProviderSource.Explicit)).Message); + () => selector.SelectServices()).Message); } private static IDatabaseProvider CreateSource(string name, bool configured, bool available)