Skip to content

Commit 909f473

Browse files
committed
Make ILoggerFactory a scoped service
Issue #14698 Main changes: * ILoggerFactory is still captured in AddDbContext, but as a wrapped scoped factory * Same thing can be done with UseLoggerFactory * No longer pathological to pass a different instance each time * IMemoryCache is no longer captured from AddDbContext * Can still be passed to UseMemoryCache * IRawSqlCommandBuilder and IMigrationsSqlGenerator have been made scoped * Validation and query compilation, method call translators, and a few more now accept the logger to use
1 parent 12a0984 commit 909f473

File tree

229 files changed

+2319
-1083
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

229 files changed

+2319
-1083
lines changed

src/EFCore.Design/Scaffolding/Internal/CSharpDbContextGenerator.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System;
55
using System.Collections.Generic;
6+
using System.Diagnostics;
67
using System.Linq;
78
using JetBrains.Annotations;
89
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
@@ -14,6 +15,7 @@
1415
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal;
1516
using Microsoft.EntityFrameworkCore.Metadata.Internal;
1617
using Microsoft.EntityFrameworkCore.Utilities;
18+
using Microsoft.Extensions.Logging;
1719

1820
namespace Microsoft.EntityFrameworkCore.Scaffolding.Internal
1921
{
@@ -636,10 +638,15 @@ private void GenerateProperty(IProperty property, bool useDataAnnotations)
636638
$"({_code.Literal(property.Relational().ComputedColumnSql)})");
637639
}
638640

641+
var dummyLogger = new DiagnosticsLogger<DbLoggerCategory.Model>(
642+
new LoggerFactory(),
643+
new LoggingOptions(),
644+
new DiagnosticListener(""));
645+
639646
var valueGenerated = property.ValueGenerated;
640647
var isRowVersion = false;
641648
if (((Property)property).GetValueGeneratedConfigurationSource().HasValue
642-
&& new RelationalValueGeneratorConvention().GetValueGenerated((Property)property) != valueGenerated)
649+
&& new RelationalValueGeneratorConvention(dummyLogger).GetValueGenerated((Property)property) != valueGenerated)
643650
{
644651
string methodName;
645652
switch (valueGenerated)

src/EFCore.Design/Scaffolding/Internal/RelationalScaffoldingModelFactory.cs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System;
55
using System.Collections.Generic;
6+
using System.Diagnostics;
67
using System.Globalization;
78
using System.Linq;
89
using JetBrains.Annotations;
@@ -18,6 +19,7 @@
1819
using Microsoft.EntityFrameworkCore.Scaffolding.Metadata;
1920
using Microsoft.EntityFrameworkCore.Scaffolding.Metadata.Internal;
2021
using Microsoft.EntityFrameworkCore.Utilities;
22+
using Microsoft.Extensions.Logging;
2123
using ScaffoldingAnnotationNames = Microsoft.EntityFrameworkCore.Scaffolding.Metadata.Internal.ScaffoldingAnnotationNames;
2224

2325
namespace Microsoft.EntityFrameworkCore.Scaffolding.Internal
@@ -476,14 +478,20 @@ protected virtual KeyBuilder VisitPrimaryKey([NotNull] EntityTypeBuilder builder
476478

477479
var keyBuilder = builder.HasKey(primaryKey.Columns.Select(GetPropertyName).ToArray());
478480

481+
479482
if (primaryKey.Columns.Count == 1
480483
&& primaryKey.Columns[0].ValueGenerated == null
481484
&& primaryKey.Columns[0].DefaultValueSql == null)
482485
{
483486
var property = builder.Metadata.FindProperty(GetPropertyName(primaryKey.Columns[0]))?.AsProperty();
484487
if (property != null)
485488
{
486-
var conventionalValueGenerated = new RelationalValueGeneratorConvention().GetValueGenerated(property);
489+
var dummyLogger = new DiagnosticsLogger<DbLoggerCategory.Model>(
490+
new LoggerFactory(),
491+
new LoggingOptions(),
492+
new DiagnosticListener(""));
493+
494+
var conventionalValueGenerated = new RelationalValueGeneratorConvention(dummyLogger).GetValueGenerated(property);
487495
if (conventionalValueGenerated == ValueGenerated.OnAdd)
488496
{
489497
property.ValueGenerated = ValueGenerated.Never;

src/EFCore.InMemory/Metadata/Conventions/Internal/InMemoryConventionSetBuilder.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System;
5+
using JetBrains.Annotations;
6+
using Microsoft.EntityFrameworkCore.Diagnostics;
57
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
68
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal;
79
using Microsoft.Extensions.DependencyInjection;
@@ -23,6 +25,21 @@ namespace Microsoft.EntityFrameworkCore.InMemory.Metadata.Conventions.Internal
2325
/// </summary>
2426
public class InMemoryConventionSetBuilder : IConventionSetBuilder
2527
{
28+
/// <summary>
29+
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
30+
/// directly from your code. This API may change or be removed in future releases.
31+
/// </summary>
32+
public InMemoryConventionSetBuilder([NotNull] IDiagnosticsLogger<DbLoggerCategory.Model> logger)
33+
{
34+
Logger = logger;
35+
}
36+
37+
/// <summary>
38+
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
39+
/// directly from your code. This API may change or be removed in future releases.
40+
/// </summary>
41+
protected virtual IDiagnosticsLogger<DbLoggerCategory.Model> Logger { get; }
42+
2643
/// <summary>
2744
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
2845
/// directly from your code. This API may change or be removed in future releases.

src/EFCore.Proxies/Proxies/Internal/ProxiesConventionSetBuilder.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using JetBrains.Annotations;
5+
using Microsoft.EntityFrameworkCore.Diagnostics;
56
using Microsoft.EntityFrameworkCore.Infrastructure;
67
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
78
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal;
@@ -28,6 +29,7 @@ public class ProxiesConventionSetBuilder : IConventionSetBuilder
2829
private readonly IDbContextOptions _options;
2930
private readonly IConstructorBindingFactory _constructorBindingFactory;
3031
private readonly IProxyFactory _proxyFactory;
32+
private readonly IDiagnosticsLogger<DbLoggerCategory.Model> _logger;
3133

3234
/// <summary>
3335
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
@@ -36,11 +38,13 @@ public class ProxiesConventionSetBuilder : IConventionSetBuilder
3638
public ProxiesConventionSetBuilder(
3739
[NotNull] IDbContextOptions options,
3840
[NotNull] IConstructorBindingFactory constructorBindingFactory,
39-
[NotNull] IProxyFactory proxyFactory)
41+
[NotNull] IProxyFactory proxyFactory,
42+
[NotNull] IDiagnosticsLogger<DbLoggerCategory.Model> logger)
4043
{
4144
_options = options;
4245
_constructorBindingFactory = constructorBindingFactory;
4346
_proxyFactory = proxyFactory;
47+
_logger = logger;
4448
}
4549

4650
/// <summary>
@@ -53,6 +57,7 @@ public virtual ConventionSet AddConventions(ConventionSet conventionSet)
5357
new ProxyBindingRewriter(
5458
_proxyFactory,
5559
_constructorBindingFactory,
60+
_logger,
5661
_options.FindExtension<ProxiesOptionsExtension>()));
5762

5863
return conventionSet;

src/EFCore.Proxies/Proxies/Internal/ProxyBindingRewriter.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Linq;
77
using System.Reflection;
88
using JetBrains.Annotations;
9+
using Microsoft.EntityFrameworkCore.Diagnostics;
910
using Microsoft.EntityFrameworkCore.Infrastructure;
1011
using Microsoft.EntityFrameworkCore.Internal;
1112
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal;
@@ -36,9 +37,10 @@ private static readonly PropertyInfo _lazyLoaderProperty
3637
public ProxyBindingRewriter(
3738
[NotNull] IProxyFactory proxyFactory,
3839
[NotNull] IConstructorBindingFactory bindingFactory,
40+
[NotNull] IDiagnosticsLogger<DbLoggerCategory.Model> logger,
3941
[CanBeNull] ProxiesOptionsExtension options)
4042
{
41-
_directBindingConvention = new ConstructorBindingConvention(bindingFactory);
43+
_directBindingConvention = new ConstructorBindingConvention(bindingFactory, logger);
4244
_proxyFactory = proxyFactory;
4345
_options = options;
4446
}

src/EFCore.Relational/Infrastructure/EntityFrameworkRelationalServicesBuilder.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,6 @@ public static readonly IDictionary<Type, ServiceCharacteristics> RelationalServi
6363
{ typeof(IMigrationsAnnotationProvider), new ServiceCharacteristics(ServiceLifetime.Singleton) },
6464
{ typeof(IMigrationCommandExecutor), new ServiceCharacteristics(ServiceLifetime.Singleton) },
6565
{ typeof(IRelationalCommandBuilderFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
66-
{ typeof(IRawSqlCommandBuilder), new ServiceCharacteristics(ServiceLifetime.Singleton) },
67-
{ typeof(IMigrationsSqlGenerator), new ServiceCharacteristics(ServiceLifetime.Singleton) },
6866
{ typeof(IRelationalTypeMappingSource), new ServiceCharacteristics(ServiceLifetime.Singleton) },
6967
{ typeof(IRelationalValueBufferFactoryFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
7068
{ typeof(IMaterializerFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
@@ -81,6 +79,8 @@ public static readonly IDictionary<Type, ServiceCharacteristics> RelationalServi
8179
{ typeof(ICommandBatchPreparer), new ServiceCharacteristics(ServiceLifetime.Scoped) },
8280
{ typeof(IModificationCommandBatchFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
8381
{ typeof(IMigrationsModelDiffer), new ServiceCharacteristics(ServiceLifetime.Scoped) },
82+
{ typeof(IMigrationsSqlGenerator), new ServiceCharacteristics(ServiceLifetime.Scoped) },
83+
{ typeof(IRawSqlCommandBuilder), new ServiceCharacteristics(ServiceLifetime.Scoped) },
8484
{ typeof(IMigrator), new ServiceCharacteristics(ServiceLifetime.Scoped) },
8585
{ typeof(IMigrationsAssembly), new ServiceCharacteristics(ServiceLifetime.Scoped) },
8686
{ typeof(IBatchExecutor), new ServiceCharacteristics(ServiceLifetime.Scoped) },
@@ -177,15 +177,16 @@ public override EntityFrameworkServicesBuilder TryAddCoreServices()
177177
.AddDependencySingleton<UpdateSqlGeneratorDependencies>()
178178
.AddDependencySingleton<QuerySqlGeneratorDependencies>()
179179
.AddDependencySingleton<RelationalCompositeMethodCallTranslatorDependencies>()
180-
.AddDependencySingleton<MigrationsSqlGeneratorDependencies>()
181180
.AddDependencySingleton<MigrationsAnnotationProviderDependencies>()
182181
.AddDependencySingleton<SqlTranslatingExpressionVisitorDependencies>()
183182
.AddDependencySingleton<ParameterNameGeneratorDependencies>()
184183
.AddDependencySingleton<SelectExpressionDependencies>()
185184
.AddDependencySingleton<RelationalValueBufferFactoryDependencies>()
186185
.AddDependencySingleton<RelationalProjectionExpressionVisitorDependencies>()
187186
.AddDependencySingleton<RelationalTransactionFactoryDependencies>()
187+
.AddDependencyScoped<MigrationsSqlGeneratorDependencies>()
188188
.AddDependencyScoped<RelationalConventionSetBuilderDependencies>()
189+
.AddDependencyScoped<ModificationCommandBatchFactoryDependencies>()
189190
.AddDependencyScoped<CommandBatchPreparerDependencies>()
190191
.AddDependencyScoped<RelationalDatabaseCreatorDependencies>()
191192
.AddDependencyScoped<HistoryRepositoryDependencies>()

src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs

Lines changed: 30 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Collections.Generic;
66
using System.Linq;
77
using JetBrains.Annotations;
8+
using Microsoft.EntityFrameworkCore.Diagnostics;
89
using Microsoft.EntityFrameworkCore.Internal;
910
using Microsoft.EntityFrameworkCore.Metadata;
1011
using Microsoft.EntityFrameworkCore.Metadata.Internal;
@@ -49,22 +50,23 @@ public RelationalModelValidator(
4950
/// Validates a model, throwing an exception if any errors are found.
5051
/// </summary>
5152
/// <param name="model"> The model to validate. </param>
52-
public override void Validate(IModel model)
53+
/// <param name="loggers"> Loggers to use. </param>
54+
public override void Validate(IModel model, DiagnosticsLoggers loggers)
5355
{
54-
base.Validate(model);
56+
base.Validate(model, loggers);
5557

56-
ValidateSharedTableCompatibility(model);
57-
ValidateInheritanceMapping(model);
58-
ValidateDefaultValuesOnKeys(model);
59-
ValidateBoolsWithDefaults(model);
60-
ValidateDbFunctions(model);
58+
ValidateSharedTableCompatibility(model, loggers);
59+
ValidateInheritanceMapping(model, loggers);
60+
ValidateDefaultValuesOnKeys(model, loggers);
61+
ValidateBoolsWithDefaults(model, loggers);
62+
ValidateDbFunctions(model, loggers);
6163
}
6264

6365
/// <summary>
6466
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
6567
/// directly from your code. This API may change or be removed in future releases.
6668
/// </summary>
67-
protected virtual void ValidateDbFunctions([NotNull] IModel model)
69+
protected virtual void ValidateDbFunctions([NotNull] IModel model, DiagnosticsLoggers loggers)
6870
{
6971
foreach (var dbFunction in model.Relational().DbFunctions)
7072
{
@@ -105,18 +107,20 @@ protected virtual void ValidateDbFunctions([NotNull] IModel model)
105107
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
106108
/// directly from your code. This API may change or be removed in future releases.
107109
/// </summary>
108-
protected virtual void ValidateBoolsWithDefaults([NotNull] IModel model)
110+
protected virtual void ValidateBoolsWithDefaults([NotNull] IModel model, DiagnosticsLoggers loggers)
109111
{
110112
Check.NotNull(model, nameof(model));
111113

114+
var logger = loggers.GetLogger<DbLoggerCategory.Model.Validation>();
115+
112116
foreach (var property in model.GetEntityTypes().SelectMany(e => e.GetDeclaredProperties()))
113117
{
114118
if (property.ClrType == typeof(bool)
115119
&& property.ValueGenerated != ValueGenerated.Never
116120
&& (IsNotNullAndFalse(property.Relational().DefaultValue)
117121
|| property.Relational().DefaultValueSql != null))
118122
{
119-
Dependencies.Logger.BoolWithDefaultWarning(property);
123+
logger.BoolWithDefaultWarning(property);
120124
}
121125
}
122126
}
@@ -129,21 +133,23 @@ private static bool IsNotNullAndFalse(object value)
129133
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
130134
/// directly from your code. This API may change or be removed in future releases.
131135
/// </summary>
132-
protected virtual void ValidateDefaultValuesOnKeys([NotNull] IModel model)
136+
protected virtual void ValidateDefaultValuesOnKeys([NotNull] IModel model, DiagnosticsLoggers loggers)
133137
{
138+
var logger = loggers.GetLogger<DbLoggerCategory.Model.Validation>();
139+
134140
foreach (var property in model.GetEntityTypes().SelectMany(
135141
t => t.GetDeclaredKeys().SelectMany(k => k.Properties))
136142
.Where(p => p.Relational().DefaultValue != null))
137143
{
138-
Dependencies.Logger.ModelValidationKeyDefaultValueWarning(property);
144+
logger.ModelValidationKeyDefaultValueWarning(property);
139145
}
140146
}
141147

142148
/// <summary>
143149
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
144150
/// directly from your code. This API may change or be removed in future releases.
145151
/// </summary>
146-
protected virtual void ValidateSharedTableCompatibility([NotNull] IModel model)
152+
protected virtual void ValidateSharedTableCompatibility([NotNull] IModel model, DiagnosticsLoggers loggers)
147153
{
148154
var tables = new Dictionary<string, List<IEntityType>>();
149155
foreach (var entityType in model.GetEntityTypes().Where(et => !et.IsQueryType))
@@ -164,11 +170,11 @@ protected virtual void ValidateSharedTableCompatibility([NotNull] IModel model)
164170
{
165171
var mappedTypes = tableMapping.Value;
166172
var tableName = tableMapping.Key;
167-
ValidateSharedTableCompatibility(mappedTypes, tableName);
168-
ValidateSharedColumnsCompatibility(mappedTypes, tableName);
169-
ValidateSharedKeysCompatibility(mappedTypes, tableName);
170-
ValidateSharedForeignKeysCompatibility(mappedTypes, tableName);
171-
ValidateSharedIndexesCompatibility(mappedTypes, tableName);
173+
ValidateSharedTableCompatibility(mappedTypes, tableName, loggers);
174+
ValidateSharedColumnsCompatibility(mappedTypes, tableName, loggers);
175+
ValidateSharedKeysCompatibility(mappedTypes, tableName, loggers);
176+
ValidateSharedForeignKeysCompatibility(mappedTypes, tableName, loggers);
177+
ValidateSharedIndexesCompatibility(mappedTypes, tableName, loggers);
172178
}
173179
}
174180

@@ -177,7 +183,7 @@ protected virtual void ValidateSharedTableCompatibility([NotNull] IModel model)
177183
/// directly from your code. This API may change or be removed in future releases.
178184
/// </summary>
179185
protected virtual void ValidateSharedTableCompatibility(
180-
[NotNull] IReadOnlyList<IEntityType> mappedTypes, [NotNull] string tableName)
186+
[NotNull] IReadOnlyList<IEntityType> mappedTypes, [NotNull] string tableName, DiagnosticsLoggers loggers)
181187
{
182188
if (mappedTypes.Count == 1)
183189
{
@@ -276,7 +282,7 @@ private static bool IsIdentifyingPrincipal(IEntityType dependentEntityType, IEnt
276282
/// directly from your code. This API may change or be removed in future releases.
277283
/// </summary>
278284
protected virtual void ValidateSharedColumnsCompatibility(
279-
[NotNull] IReadOnlyList<IEntityType> mappedTypes, [NotNull] string tableName)
285+
[NotNull] IReadOnlyList<IEntityType> mappedTypes, [NotNull] string tableName, DiagnosticsLoggers loggers)
280286
{
281287
var propertyMappings = new Dictionary<string, IProperty>();
282288

@@ -377,7 +383,7 @@ protected virtual void ValidateSharedColumnsCompatibility(
377383
/// directly from your code. This API may change or be removed in future releases.
378384
/// </summary>
379385
protected virtual void ValidateSharedForeignKeysCompatibility(
380-
[NotNull] IReadOnlyList<IEntityType> mappedTypes, [NotNull] string tableName)
386+
[NotNull] IReadOnlyList<IEntityType> mappedTypes, [NotNull] string tableName, DiagnosticsLoggers loggers)
381387
{
382388
var foreignKeyMappings = new Dictionary<string, IForeignKey>();
383389

@@ -399,7 +405,7 @@ protected virtual void ValidateSharedForeignKeysCompatibility(
399405
/// directly from your code. This API may change or be removed in future releases.
400406
/// </summary>
401407
protected virtual void ValidateSharedIndexesCompatibility(
402-
[NotNull] IReadOnlyList<IEntityType> mappedTypes, [NotNull] string tableName)
408+
[NotNull] IReadOnlyList<IEntityType> mappedTypes, [NotNull] string tableName, DiagnosticsLoggers loggers)
403409
{
404410
var indexMappings = new Dictionary<string, IIndex>();
405411

@@ -421,7 +427,7 @@ protected virtual void ValidateSharedIndexesCompatibility(
421427
/// directly from your code. This API may change or be removed in future releases.
422428
/// </summary>
423429
protected virtual void ValidateSharedKeysCompatibility(
424-
[NotNull] IReadOnlyList<IEntityType> mappedTypes, [NotNull] string tableName)
430+
[NotNull] IReadOnlyList<IEntityType> mappedTypes, [NotNull] string tableName, DiagnosticsLoggers loggers)
425431
{
426432
var keyMappings = new Dictionary<string, IKey>();
427433

@@ -456,7 +462,7 @@ protected virtual void ValidateSharedKeysCompatibility(
456462
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
457463
/// directly from your code. This API may change or be removed in future releases.
458464
/// </summary>
459-
protected virtual void ValidateInheritanceMapping([NotNull] IModel model)
465+
protected virtual void ValidateInheritanceMapping([NotNull] IModel model, DiagnosticsLoggers loggers)
460466
{
461467
foreach (var rootEntityType in model.GetRootEntityTypes())
462468
{

0 commit comments

Comments
 (0)