Exemplo n.º 1
0
        private static IDataContext GetPerpetuumDatabases(IServiceProvider container, IConfiguration configuration)
        {
            IEnumerable <Assembly> asm = AssemblyLoader.Instance.RuntimeAssemblies;
            var providers = asm.SelectMany(a => a.DefinedTypes).Where(type => typeof(IDatabaseProvider).IsAssignableFrom(type.AsType()));

            IDataContext dataContext            = new DataContext();
            var          databaseConfigurations = container.GetService(typeof(IOptions <DataProviderConfiguration>)) as IOptions <DataProviderConfiguration>;

            foreach (var dbConfig in databaseConfigurations.Value.Databases)
            {
                IDatabaseProvider provider;
                try
                {
                    var providerType     = providers.Single(ti => ti.Name.StartsWith(dbConfig.Type));
                    var connectionString = configuration.GetConnectionString(dbConfig.ConnectionId);
                    provider = Activator.CreateInstance(providerType.AsType(), new object[] { dbConfig.ProviderName, connectionString }) as IDatabaseProvider;
                }
                catch (InvalidOperationException ioe)
                {
                    throw new InvalidOperationException($"Could not find a single DB provider of type \"{dbConfig.ProviderName}\"", ioe);
                }
                catch (Exception exc)
                {
                    throw new InvalidOperationException($"Unable to activate an instance of type \"{dbConfig.ProviderName}\". Please see inner exception details.", exc);
                }
                dataContext.AddDataContext(provider);
            }

            return(dataContext);
        }