-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathDbContextManager.cs
More file actions
233 lines (194 loc) · 9.34 KB
/
Copy pathDbContextManager.cs
File metadata and controls
233 lines (194 loc) · 9.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Copyright (c) 2026 Phoenix Contact GmbH & Co. KG
// Licensed under the Apache License, Version 2.0
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moryx.Configuration;
using Moryx.Model.Attributes;
using Moryx.Model.Configuration;
using Moryx.Tools;
namespace Moryx.Model;
/// <summary>
/// Kernel component handling data models and their runtime configurators
/// </summary>
public class DbContextManager : IDbContextManager
{
private readonly ILoggerFactory _loggerFactory;
private readonly IConfigManager _configManager;
private readonly ConfiguredModelWrapper[] _configuredModels;
private readonly PossibleModelWrapper[] _possibleModels;
/// <summary>
/// Initializes a new instance of the <see cref="DbContextManager"/> class.
/// </summary>
/// <param name="configManager">Dependency to load model related configurations</param>
/// <param name="loggerFactory">Logger factory to provide the <see cref="IModelConfigurator"/> a logger</param>
public DbContextManager(IConfigManager configManager, ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
_configManager = configManager;
_possibleModels = GetPossibleModels();
_configuredModels = GetConfiguredModels();
foreach (var wrapper in _configuredModels)
{
InitializeConfigurator(wrapper);
}
}
/// <summary>
/// This method uses reflection to find all possible models in the current AppDomain
/// </summary>
private static PossibleModelWrapper[] GetPossibleModels()
{
var possibleModels = ReflectionTool.GetPublicClasses(typeof(DbContext))
.Where(type => type != typeof(DbContext) && typeof(DbContext).IsAssignableFrom(type) &&
!type.IsAbstract &&
type.GetCustomAttributes<DatabaseTypeSpecificDbContextAttribute>().Any())
.SelectMany(type =>
{
var dbTypeAttributes = type.GetCustomAttributes<DatabaseTypeSpecificDbContextAttribute>()!;
return dbTypeAttributes.Select(attr => new
{
DbContextType = type, BaseDbContextType = attr.BaseDbContextType ?? type, ModelConfiguratorType = attr.ModelConfiguratorType
});
}).GroupBy(pc => pc.BaseDbContextType).Select(g =>
{
var modelConfiguratorMap = g.ToDictionary(x => x.ModelConfiguratorType, x => x.DbContextType);
return new PossibleModelWrapper { DbContext = g.Key, ModelConfiguratorMap = modelConfiguratorMap };
}).ToArray();
return possibleModels;
}
/// <summary>
/// This method loads all configured models with support of the <see cref="IConfigManager"/>
/// It matches the configured models with the possible models and creates them
/// </summary>
private ConfiguredModelWrapper[] GetConfiguredModels()
{
var configuredModels = new List<ConfiguredModelWrapper>();
foreach (var possibleModel in _possibleModels)
{
var config = _configManager.GetConfiguration<DatabaseConfig>(ConfigFilename(possibleModel.DbContext));
Type configuratorType = null;
Type specificDbContextType = null;
if (!string.IsNullOrEmpty(config.ConfiguratorType))
{
var configuredConfiguratorType = Type.GetType(config.ConfiguratorType);
if (configuredConfiguratorType != null &&
possibleModel.ModelConfiguratorMap.TryGetValue(configuredConfiguratorType, out specificDbContextType))
{
configuratorType = configuredConfiguratorType;
}
}
else
{
var defaultMatch = possibleModel.ModelConfiguratorMap.FirstOrDefault();
if (!defaultMatch.Equals(default(KeyValuePair<Type, Type>)))
{
configuratorType = defaultMatch.Key;
specificDbContextType = defaultMatch.Value;
}
}
if (configuratorType == null || specificDbContextType == null)
throw new InvalidOperationException($"No valid configurator found for DbContext '{possibleModel.DbContext.FullName}'");
var configType = configuratorType.BaseType.GenericTypeArguments.First();
var typedConfig = (DatabaseConfig)_configManager.GetConfiguration(configType,
ConfigFilename(possibleModel.DbContext), true);
if (string.IsNullOrEmpty(typedConfig.ConnectionString))
{
typedConfig.UpdateConnectionString();
}
else
{
typedConfig.UpdatePropertiesFromConnectionString();
}
configuredModels.Add(new ConfiguredModelWrapper
{
BaseDbContextType = possibleModel.DbContext,
SpecificDbContextType = specificDbContextType,
DatabaseConfig = typedConfig,
Configurator = (IModelConfigurator)Activator.CreateInstance(configuratorType)
});
}
return configuredModels.ToArray();
}
/// <inheritdoc />
public void UpdateConfig(Type dbContextType, Type configuratorType, DatabaseConfig databaseConfig)
{
_configManager.SaveConfiguration(databaseConfig, ConfigFilename(dbContextType));
var modelWrapper = _configuredModels.First(w => w.BaseDbContextType == dbContextType);
Type specificDbContextType = null;
_possibleModels.FirstOrDefault(pm => pm.DbContext == dbContextType)?.ModelConfiguratorMap.TryGetValue(configuratorType, out specificDbContextType);
modelWrapper.SpecificDbContextType = specificDbContextType;
modelWrapper.Configurator = (IModelConfigurator)Activator.CreateInstance(configuratorType);
modelWrapper.DatabaseConfig = databaseConfig;
InitializeConfigurator(modelWrapper);
}
private void InitializeConfigurator(ConfiguredModelWrapper configuredModelWrapper)
{
var configuratorType = configuredModelWrapper.Configurator.GetType();
var logger = _loggerFactory.CreateLogger(configuratorType);
configuredModelWrapper.Configurator.Initialize(configuredModelWrapper.SpecificDbContextType, configuredModelWrapper.DatabaseConfig, logger);
}
private static string ConfigFilename(Type dbContextType)
=> dbContextType.FullName + ".DbConfig";
/// <inheritdoc />
public IReadOnlyCollection<Type> Contexts => _configuredModels.Select(km => km.BaseDbContextType).ToArray();
/// <inheritdoc />
public IModelConfigurator GetConfigurator(Type contextType) =>
_configuredModels.First(km => km.BaseDbContextType == contextType).Configurator;
public IModelConfigurator GetConfigurator(Type contextType, Type configuratorType, DatabaseConfig databaseConfig)
{
var possibleModel = _possibleModels.FirstOrDefault(pm => pm.DbContext == contextType);
if (possibleModel == null)
return null;
if (possibleModel.ModelConfiguratorMap.TryGetValue(configuratorType, out var specificDbContextType))
{
var configuratorInstance = (IModelConfigurator)Activator.CreateInstance(configuratorType)!;
var logger = _loggerFactory.CreateLogger(configuratorType);
configuratorInstance.Initialize(specificDbContextType, databaseConfig, logger);
return configuratorInstance;
}
else
{
return null;
}
}
/// <inheritdoc />
public Type[] GetConfigurators(Type contextType)
{
return _possibleModels.FirstOrDefault(pm => pm.DbContext == contextType)?.ModelConfiguratorMap.Keys.ToArray();
}
/// <inheritdoc />
public IModelSetupExecutor GetSetupExecutor(Type contextType)
{
var configuredContext = _configuredModels.FirstOrDefault(m => m.BaseDbContextType == contextType);
if (configuredContext == null)
throw new InvalidOperationException($"Context {contextType.FullName} not configured!");
var setupExecutorType = typeof(ModelSetupExecutor<>).MakeGenericType(configuredContext.BaseDbContextType);
return (IModelSetupExecutor)Activator.CreateInstance(setupExecutorType, this);
}
/// <inheritdoc />
public TContext Create<TContext>() where TContext : DbContext =>
Create<TContext>(null);
/// <inheritdoc />
public TContext Create<TContext>(DatabaseConfig config) where TContext : DbContext
{
var wrapper = _configuredModels.FirstOrDefault(k => k.BaseDbContextType == typeof(TContext));
if (wrapper == null)
throw new InvalidOperationException("Unknown model");
var configurator = wrapper.Configurator;
return config != null
? (TContext)configurator.CreateContext(config)
: (TContext)configurator.CreateContext();
}
private class ConfiguredModelWrapper
{
public Type BaseDbContextType { get; set; }
public Type SpecificDbContextType { get; set; }
public IModelConfigurator Configurator { get; set; }
public DatabaseConfig DatabaseConfig { get; set; }
}
private class PossibleModelWrapper
{
public Type DbContext { get; set; }
public Dictionary<Type, Type> ModelConfiguratorMap { get; set; }
}
}