public static IEnumerable<EntitySet> Convert( IList<EntitySet> sourceEntitySets, Version targetEntityFrameworkVersion, string providerInvariantName, string providerManifestToken, IDbDependencyResolver dependencyResolver) { Debug.Assert(sourceEntitySets != null, "sourceEntitySets != null"); Debug.Assert(sourceEntitySets.All(e => e.DefiningQuery == null), "unexpected defining query"); Debug.Assert(!string.IsNullOrWhiteSpace(providerInvariantName), "invalid providerInvariantName"); Debug.Assert(!string.IsNullOrWhiteSpace(providerManifestToken), "invalid providerManifestToken"); Debug.Assert(dependencyResolver != null, "dependencyResolver != null"); if (!sourceEntitySets.Any()) { // it's empty anyways return sourceEntitySets; } var providerServices = dependencyResolver.GetService<DbProviderServices>(providerInvariantName); Debug.Assert(providerServices != null, "providerServices != null"); var transientWorkspace = CreateTransientMetadataWorkspace( sourceEntitySets, targetEntityFrameworkVersion, providerInvariantName, providerManifestToken, providerServices.GetProviderManifest(providerManifestToken)); return sourceEntitySets.Select( e => CloneWithDefiningQuery( e, CreateDefiningQuery(e, transientWorkspace, providerServices))); }
/// <summary> /// Ask for a spatial provider. If one has been registered then we will use it, otherwise we will /// fall back on using the SQL provider and if this is not available then the default provider. /// </summary> public virtual DbSpatialServices LoadDefaultServices() { var spatialProvider = _resolver.GetService <DbSpatialServices>(); if (spatialProvider != null) { return(spatialProvider); } var efProvider = _resolver.GetService <DbProviderServices>("System.Data.SqlClient"); Debug.Assert(efProvider != null); try { spatialProvider = efProvider.GetSpatialServicesInternal(new Lazy <IDbDependencyResolver>(() => _resolver), "2008"); if (spatialProvider.NativeTypesAvailable) { return(spatialProvider); } } catch (ProviderIncompatibleException) { // Thrown if the provider doesn't support spatial, in which case we fall back to the default. } return(DefaultSpatialServices.Instance); }
/// <summary> /// Calls <see cref="IDbDependencyResolver.GetService" /> passing the given type argument and using /// null for the name argument. /// </summary> /// <param name="resolver"> The resolver to use. </param> /// <param name="type"> The contract type to resolve. </param> /// <returns> The resolved dependency, or null if the resolver could not resolve it. </returns> public static object GetService(this IDbDependencyResolver resolver, Type type) { Check.NotNull(resolver, "resolver"); Check.NotNull(type, "type"); return(resolver.GetService(type, null)); }
internal void WriteExtendedProperties(MetadataItem item) { DebugCheck.NotNull(item); foreach (var extendedProperty in item.MetadataProperties.Where(p => p.PropertyKind == PropertyKind.Extended)) { // We have to special case StoreGeneratedPattern because even though it is an "extended" property we have // special handling for it elsewhere, which means if we try to serialize it like a normal extended property // we might end up with duplicate attributes in the XML. string xmlNamespaceUri, attributeName; if (TrySplitExtendedMetadataPropertyName(extendedProperty.Name, out xmlNamespaceUri, out attributeName) && extendedProperty.Name != XmlConstants.StoreGeneratedPatternAnnotation) { DebugCheck.NotNull(extendedProperty.Value); var serializer = _resolver.GetService <Func <IMetadataAnnotationSerializer> >(attributeName); var value = serializer == null ? extendedProperty.Value.ToString() : serializer().Serialize(attributeName, extendedProperty.Value); _xmlWriter.WriteAttributeString(attributeName, xmlNamespaceUri, value); } } }
internal static string GetProviderManifestTokenConnected( IDbDependencyResolver resolver, string providerInvariantName, string providerConnectionString) { DbConnection connection = null; try { var factory = DbProviderFactories.GetFactory(providerInvariantName); Debug.Assert(factory != null, "failed because DbProviderFactory is null"); connection = factory.CreateConnection(); Debug.Assert(connection != null, "failed because DbConnection is null"); connection.ConnectionString = providerConnectionString; var providerServices = resolver.GetService <DbProviderServices>(providerInvariantName); Debug.Assert(providerServices != null, "failed because DbProviderServices is null"); return(providerServices.GetProviderManifestToken(connection)); } finally { VsUtils.SafeCloseDbConnection(connection, providerInvariantName, providerConnectionString); } }
public StoreModelBuilder( string providerInvariantName, string providerManifestToken, Version targetEntityFrameworkVersion, string namespaceName, IDbDependencyResolver resolver, bool generateForeignKeyProperties) { Debug.Assert( !string.IsNullOrWhiteSpace(providerInvariantName), "!string.IsNullOrWhiteSpace(providerInvariantName"); Debug.Assert( !string.IsNullOrWhiteSpace(providerManifestToken), "!string.IsNullOrWhiteSpace(providerManifestToken"); Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetEntityFrameworkVersion), "invalid entityFrameworkVersion"); Debug.Assert(!string.IsNullOrWhiteSpace(namespaceName), "!string.IsNullOrWhiteSpace(namespaceName)"); Debug.Assert(resolver != null, "resolver != null"); _providerInvariantName = providerInvariantName; _providerManifestToken = providerManifestToken; _targetEntityFrameworkVersion = targetEntityFrameworkVersion; _namespaceName = namespaceName; _dependencyResolver = resolver; _generateForeignKeyProperties = generateForeignKeyProperties; var providerServices = resolver.GetService<DbProviderServices>(providerInvariantName); Debug.Assert(providerServices != null, "providerServices != null"); _nameToEdmType = providerServices.GetProviderManifest(providerManifestToken) .GetStoreTypes() .ToDictionary(t => t.Name, t => t); }
// <summary> // Creates a database using the core provider (i.e. ObjectContext.CreateDatabase) or // by using Code First Migrations <see cref="DbMigrator" /> to create an empty database // and the perform an automatic migration to the current model. // </summary> public virtual void CreateDatabase( InternalContext internalContext, Func <DbMigrationsConfiguration, DbContext, MigratorBase> createMigrator, ObjectContext objectContext) { DebugCheck.NotNull(internalContext); DebugCheck.NotNull(createMigrator); // objectContext may be null when testing. if (internalContext.CodeFirstModel != null && _resolver.GetService <Func <MigrationSqlGenerator> >(internalContext.ProviderName) != null) { createMigrator( internalContext.MigrationsConfiguration, internalContext.Owner).Update(); } else { internalContext.DatabaseOperations.Create(objectContext); internalContext.SaveMetadataToDatabase(); } // If the database is created explicitly, then this is treated as overriding the // database initialization strategy, so make it as already run. internalContext.MarkDatabaseInitialized(); }
internal MetadataProperty CreateMetadataPropertyFromXmlAttribute( string xmlNamespaceUri, string attributeName, string value) { var serializer = _resolver.GetService <Func <IMetadataAnnotationSerializer> >(attributeName); var parsedValue = serializer == null ? value : serializer().Deserialize(attributeName, value); return(MetadataProperty.CreateAnnotation(xmlNamespaceUri + ":" + attributeName, parsedValue)); }
// <summary> // Ask for a spatial provider. If one has been registered then we will use it, otherwise we will // fall back on using the SQL provider and if this is not available then the default provider. // </summary> public virtual DbSpatialServices LoadDefaultServices() { var spatialProvider = _resolver.GetService <DbSpatialServices>(); if (spatialProvider != null) { return(spatialProvider); } spatialProvider = _resolver.GetService <DbSpatialServices>(new DbProviderInfo("System.Data.SqlClient", "2012")); if (spatialProvider != null && spatialProvider.NativeTypesAvailable) { return(spatialProvider); } return(DefaultSpatialServices.Instance); }
// <summary> // This is a helper method that can be used in an <see cref="IDbDependencyResolver.GetServices"/> implementation // such that an empty list is returned if the <see cref="IDbDependencyResolver.GetService"/> returns null // and a list of one element is returned if GetService returns one element. // </summary> // <param name="resolver">The resolver.</param> // <param name="type"> The contract type to resolve. </param> // <param name="key"> The key of the dependency to resolve. </param> // <returns>A list of either zero or one elements.</returns> internal static IEnumerable <object> GetServiceAsServices(this IDbDependencyResolver resolver, Type type, object key) { DebugCheck.NotNull(resolver); var service = resolver.GetService(type, key); return(service == null?Enumerable.Empty <object>() : new[] { service }); }
internal MetadataProperty CreateMetadataPropertyFromXmlAttribute( string xmlNamespaceUri, string artifactName, string value) { var name = xmlNamespaceUri + ":" + artifactName; var serializer = _resolver.GetService <IMetadataAnnotationSerializer>(name); var parsedValue = serializer == null ? value : serializer.DeserializeValue(name, value); return(MetadataProperty.CreateAnnotation(name, parsedValue)); }
public object GetService(Type type, object key) { if (type == typeof(TService)) { return(_serviceWrapper(_snapshot.GetService <TService>(key), key)); } return(null); }
/// <summary> /// Ask for a spatial provider. If one has been registered then we will use it, otherwise we will /// fall back on using the SQL provider and if this is not available then the default provider. /// </summary> public virtual DbSpatialServices LoadDefaultServices() { var spatialProvider = _resolver.GetService <DbSpatialServices>(); if (spatialProvider != null) { return(spatialProvider); } // Note: Manifest token is currently ignored for SQL Server spatial provider spatialProvider = _resolver.GetService <DbSpatialServices>(new DbProviderInfo("System.Data.SqlClient", "2012")); if (spatialProvider != null && spatialProvider.NativeTypesAvailable) { return(spatialProvider); } return(DefaultSpatialServices.Instance); }
private void StartLogging(IDbDependencyResolver resolver) { if (this._formatter != null) { return; } this._formatter = resolver.GetService <Func <DbContext, Action <string>, DatabaseLogFormatter> >()((DbContext)null, this._writer == null ? new Action <string>(Console.Write) : new Action <string>(this.WriteThreadSafe)); DbInterception.Add((IDbInterceptor)this._formatter); }
public object GetService(Type type, object key) { if (_autofacContainer.IsRegistered(type)) { return(key != null?_autofacContainer.ResolveKeyed(key, type) : _autofacContainer.Resolve(type)); } return(_snapshot.GetService(type, key)); }
private void StartLogging(IDbDependencyResolver resolver) { DebugCheck.NotNull(resolver); if (_formatter == null) { _formatter = resolver.GetService<Func<DbContext, Action<string>, DatabaseLogFormatter>>()( null, _writer == null ? (Action<string>)Console.Write : WriteThreadSafe); DbInterception.Add(_formatter); } }
private static DbSpatialServices GetSpatialServices( IDbDependencyResolver resolver, DbProviderInfo key, Func <DbProviderServices> providerServices) // Delegate use to avoid lookup when not needed { DebugCheck.NotNull(resolver); DebugCheck.NotNull(key); DebugCheck.NotNull(providerServices); var services = _spatialServices.GetOrAdd( key, k => resolver.GetService <DbSpatialServices>(k) ?? providerServices().GetSpatialServicesInternal(k.ProviderManifestToken, throwIfNotImplemented: false) ?? resolver.GetService <DbSpatialServices>()); if (services == null) { throw new ProviderIncompatibleException(Strings.ProviderDidNotReturnSpatialServices); } return(services); }
private static DbSpatialServices GetSpatialServices( IDbDependencyResolver resolver, DbProviderInfo key, Func <DbProviderServices> providerServices) // Delegate use to avoid lookup when not needed { DebugCheck.NotNull(resolver); DebugCheck.NotNull(key); DebugCheck.NotNull(providerServices); #pragma warning disable 612, 618 var services = _spatialServices.GetOrAdd( key, k => resolver.GetService <DbSpatialServices>(k) ?? providerServices().GetSpatialServices(k.ProviderManifestToken) ?? resolver.GetService <DbSpatialServices>()); #pragma warning restore 612, 618 if (services == null) { throw new ProviderIncompatibleException(Strings.ProviderDidNotReturnSpatialServices); } return(services); }
public object GetService(Type type, object key) { if (type == typeof(IDbProviderFactoryService)) { var innerFactoryService = (IDbProviderFactoryService)rootResolver.GetService(type, key); if (!(innerFactoryService is GlimpseDbProviderFactoryService)) { return(new GlimpseDbProviderFactoryService(innerFactoryService)); } return(innerFactoryService); } if (type == typeof(DbProviderServices)) { // Would love to be able to wrap this but the ProviderServices is sealed and an "internal virual" // method needs to be overriden to return the innter type rather than the inherited type. if ((string)key == "System.Data.Entity.Core.EntityClient.EntityProviderFactory") { return(((IServiceProvider)System.Data.Entity.Core.EntityClient.EntityProviderFactory.Instance).GetService(type)); } var innerProviderServices = (DbProviderServices)rootResolver.GetService(type, key); if (!(innerProviderServices is GlimpseDbProviderServices)) { return(new GlimpseDbProviderServices(innerProviderServices)); } return(innerProviderServices); } if (type == typeof(IProviderInvariantName)) { } return(null); }
private static MetadataWorkspace GetProviderSchemaMetadataWorkspace( IDbDependencyResolver resolver, string providerInvariantName, SystemDataCommon.DbConnection providerConnection, Version targetSchemaVersion) { Debug.Assert(resolver != null, "resolver != null"); Debug.Assert(!string.IsNullOrWhiteSpace(providerInvariantName), "providerInvarianName cannot be null or empty"); Debug.Assert(providerConnection != null, "providerConnection != null"); Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetSchemaVersion), "invalid targetSchemaVersion"); string csdlName; string ssdlName; string mslName; if (targetSchemaVersion >= EntityFrameworkVersion.Version3) { csdlName = DbProviderManifest.ConceptualSchemaDefinitionVersion3; ssdlName = DbProviderManifest.StoreSchemaDefinitionVersion3; mslName = DbProviderManifest.StoreSchemaMappingVersion3; } else { csdlName = DbProviderManifest.ConceptualSchemaDefinition; ssdlName = DbProviderManifest.StoreSchemaDefinition; mslName = DbProviderManifest.StoreSchemaMapping; } var providerServices = resolver.GetService <DbProviderServices>(providerInvariantName); Debug.Assert(providerServices != null, "Trying to get unregistered provider."); var providerManifest = providerServices.GetProviderManifest( providerServices.GetProviderManifestToken(providerConnection)); var edmItemCollection = LoadEdmItemCollection(csdlName); var storeItemCollection = LoadStoreItemCollection(providerManifest, ssdlName); var mappingItemCollection = LoadMappingItemCollection(providerManifest, mslName, edmItemCollection, storeItemCollection); var workspace = new MetadataWorkspace( () => edmItemCollection, () => storeItemCollection, () => mappingItemCollection); // TODO: there is currently no public surface to do this (workitem 606 on codeplex) //// make the views generate here so we can wrap the provider schema problems //// in a ProviderIncompatibleException //ForceViewGeneration(workspace); return(workspace); }
internal virtual string GetProviderServicesInternal(string invariantName) { DbConfiguration.LoadConfiguration(this._assembly); IDbDependencyResolver dependencyResolver = DbConfiguration.DependencyResolver; DbProviderServices providerServices = (DbProviderServices)null; try { providerServices = dependencyResolver.GetService <DbProviderServices>((object)invariantName); } catch { } return(providerServices?.GetType().AssemblyQualifiedName); }
internal static IEnumerable <object> GetServiceAsServices( this IDbDependencyResolver resolver, Type type, object key) { object service = resolver.GetService(type, key); if (service == null) { return(Enumerable.Empty <object>()); } return((IEnumerable <object>) new object[1] { service }); }
private void InitializeProviderManifest(Action <string, ErrorCode, EdmSchemaErrorSeverity> addError) { if (_providerManifest == null && (_providerManifestToken != null && _provider != null)) { DbProviderFactory factory = null; try { factory = DbConfiguration.GetService <DbProviderFactory>(_provider); } catch (ArgumentException e) { addError(e.Message, ErrorCode.InvalidProvider, EdmSchemaErrorSeverity.Error); return; } try { var services = _resolver.GetService <DbProviderServices>(_provider); DebugCheck.NotNull(services); _providerManifest = services.GetProviderManifest(_providerManifestToken); _providerFactory = factory; if (_providerManifest is EdmProviderManifest) { if (_throwOnError) { throw new NotSupportedException(Strings.OnlyStoreConnectionsSupported); } else { addError(Strings.OnlyStoreConnectionsSupported, ErrorCode.InvalidProvider, EdmSchemaErrorSeverity.Error); } return; } } catch (ProviderIncompatibleException e) { if (_throwOnError) { // we want to surface these as ProviderIncompatibleExceptions if we are "allowed" to. throw; } AddProviderIncompatibleError(e, addError); } } }
/// <summary> /// Creates a database using the core provider (i.e. ObjectContext.CreateDatabase) or /// by using Code First Migrations <see cref="DbMigrator" /> to create an empty database /// and the perform an automatic migration to the current model. /// Migrations is used if Code First is being used and the EF provider is for SQL Server /// or SQL Compact. The core is used for non-Code First models and for other providers even /// when using Code First. /// </summary> public virtual void CreateDatabase( InternalContext internalContext, Func <DbMigrationsConfiguration, DbContext, MigratorBase> createMigrator, ObjectContext objectContext) { DebugCheck.NotNull(internalContext); DebugCheck.NotNull(createMigrator); // objectContext may be null when testing. if (internalContext.CodeFirstModel != null && _resolver.GetService <MigrationSqlGenerator>(internalContext.ProviderName) != null) { var contextType = internalContext.Owner.GetType(); var migrator = createMigrator( new DbMigrationsConfiguration { ContextType = contextType, AutomaticMigrationsEnabled = true, MigrationsAssembly = contextType.Assembly, MigrationsNamespace = contextType.Namespace, ContextKey = internalContext.ContextKey, TargetDatabase = new DbConnectionInfo( internalContext.OriginalConnectionString, internalContext.ProviderName) }, internalContext.Owner); migrator.Update(); } else { internalContext.DatabaseOperations.Create(objectContext); internalContext.SaveMetadataToDatabase(); } // If the database is created explicitly, then this is treated as overriding the // database initialization strategy, so make it as already run. internalContext.MarkDatabaseInitialized(); }
public static DbProviderManifest GetProviderManifest( this DbModel model, IDbDependencyResolver dependencyResolver) { Debug.Assert(model != null, "model is null."); Debug.Assert(dependencyResolver != null, "dependencyResolver is null."); if (model.ProviderManifest != null) { return model.ProviderManifest; } DbProviderManifest providerManifest; if (!_providerManifestCache.TryGetValue(model.ProviderInfo, out providerManifest)) { providerManifest = dependencyResolver .GetService<DbProviderServices>(model.ProviderInfo.ProviderInvariantName) .GetProviderManifest(model.ProviderInfo.ProviderManifestToken); _providerManifestCache.Add(model.ProviderInfo, providerManifest); } return providerManifest; }
public static IEnumerable <EntitySet> Convert( IList <EntitySet> sourceEntitySets, Version targetEntityFrameworkVersion, string providerInvariantName, string providerManifestToken, IDbDependencyResolver dependencyResolver) { Debug.Assert(sourceEntitySets != null, "sourceEntitySets != null"); Debug.Assert(sourceEntitySets.All(e => e.DefiningQuery == null), "unexpected defining query"); Debug.Assert(!string.IsNullOrWhiteSpace(providerInvariantName), "invalid providerInvariantName"); Debug.Assert(!string.IsNullOrWhiteSpace(providerManifestToken), "invalid providerManifestToken"); Debug.Assert(dependencyResolver != null, "dependencyResolver != null"); if (!sourceEntitySets.Any()) { // it's empty anyways return(sourceEntitySets); } var providerServices = dependencyResolver.GetService <DbProviderServices>(providerInvariantName); Debug.Assert(providerServices != null, "providerServices != null"); var transientWorkspace = CreateTransientMetadataWorkspace( sourceEntitySets, targetEntityFrameworkVersion, providerInvariantName, providerManifestToken, providerServices.GetProviderManifest(providerManifestToken)); return(sourceEntitySets.Select( e => CloneWithDefiningQuery( e, CreateDefiningQuery(e, transientWorkspace, providerServices)))); }
public static DbProviderManifest GetProviderManifest( this DbModel model, IDbDependencyResolver dependencyResolver) { Debug.Assert(model != null, "model is null."); Debug.Assert(dependencyResolver != null, "dependencyResolver is null."); if (model.ProviderManifest != null) { return(model.ProviderManifest); } DbProviderManifest providerManifest; if (!_providerManifestCache.TryGetValue(model.ProviderInfo, out providerManifest)) { providerManifest = dependencyResolver .GetService <DbProviderServices>(model.ProviderInfo.ProviderInvariantName) .GetProviderManifest(model.ProviderInfo.ProviderManifestToken); _providerManifestCache.Add(model.ProviderInfo, providerManifest); } return(providerManifest); }
/// <summary> /// Calls <see cref="M:System.Data.Entity.Infrastructure.DependencyResolution.IDbDependencyResolver.GetService(System.Type,System.Object)" /> passing the given type argument and using /// null for the name argument. /// </summary> /// <param name="resolver"> The resolver to use. </param> /// <param name="type"> The contract type to resolve. </param> /// <returns> The resolved dependency, or null if the resolver could not resolve it. </returns> public static object GetService(this IDbDependencyResolver resolver, Type type) { Check.NotNull <IDbDependencyResolver>(resolver, nameof(resolver)); Check.NotNull <Type>(type, nameof(type)); return(resolver.GetService(type, (object)null)); }
private static MetadataWorkspace GetProviderSchemaMetadataWorkspace( IDbDependencyResolver resolver, string providerInvariantName, SystemDataCommon.DbConnection providerConnection, Version targetSchemaVersion) { Debug.Assert(resolver != null, "resolver != null"); Debug.Assert(!string.IsNullOrWhiteSpace(providerInvariantName), "providerInvarianName cannot be null or empty"); Debug.Assert(providerConnection != null, "providerConnection != null"); Debug.Assert(EntityFrameworkVersion.IsValidVersion(targetSchemaVersion), "invalid targetSchemaVersion"); string csdlName; string ssdlName; string mslName; if (targetSchemaVersion >= EntityFrameworkVersion.Version3) { csdlName = DbProviderManifest.ConceptualSchemaDefinitionVersion3; ssdlName = DbProviderManifest.StoreSchemaDefinitionVersion3; mslName = DbProviderManifest.StoreSchemaMappingVersion3; } else { csdlName = DbProviderManifest.ConceptualSchemaDefinition; ssdlName = DbProviderManifest.StoreSchemaDefinition; mslName = DbProviderManifest.StoreSchemaMapping; } var providerServices = resolver.GetService<DbProviderServices>(providerInvariantName); Debug.Assert(providerServices != null, "Trying to get unregistered provider."); var providerManifest = providerServices.GetProviderManifest( providerServices.GetProviderManifestToken(providerConnection)); var edmItemCollection = LoadEdmItemCollection(csdlName); var storeItemCollection = LoadStoreItemCollection(providerManifest, ssdlName); var mappingItemCollection = LoadMappingItemCollection(providerManifest, mslName, edmItemCollection, storeItemCollection); var workspace = new MetadataWorkspace( () => edmItemCollection, () => storeItemCollection, () => mappingItemCollection); // TODO: there is currently no public surface to do this (workitem 606 on codeplex) //// make the views generate here so we can wrap the provider schema problems //// in a ProviderIncompatibleException //ForceViewGeneration(workspace); return workspace; }
private void StartLogging(IDbDependencyResolver resolver) { DebugCheck.NotNull(resolver); if (_formatter == null) { _formatter = resolver.GetService<Func<DbContext, Action<string>, DatabaseLogFormatter>>()( null, WriteThreadSafe); DbInterception.Add(_formatter); } }
private static DbSpatialServices GetSpatialServices( IDbDependencyResolver resolver, DbProviderInfo key, Func<DbProviderServices> providerServices) // Delegate use to avoid lookup when not needed { DebugCheck.NotNull(resolver); DebugCheck.NotNull(key); DebugCheck.NotNull(providerServices); #pragma warning disable 612, 618 var services = _spatialServices.GetOrAdd( key, k => resolver.GetService<DbSpatialServices>(k) ?? providerServices().GetSpatialServices(k.ProviderManifestToken) ?? resolver.GetService<DbSpatialServices>()); #pragma warning restore 612, 618 if (services == null) { throw new ProviderIncompatibleException(Strings.ProviderDidNotReturnSpatialServices); } return services; }
/// <summary> /// Calls <see cref="M:System.Data.Entity.Infrastructure.DependencyResolution.IDbDependencyResolver.GetService(System.Type,System.Object)" /> passing the generic type of the method as /// the type argument and null for the name argument. /// </summary> /// <typeparam name="T"> The contract type to resolve. </typeparam> /// <param name="resolver"> The resolver to use. </param> /// <returns> The resolved dependency, or null if the resolver could not resolve it. </returns> public static T GetService <T>(this IDbDependencyResolver resolver) { Check.NotNull <IDbDependencyResolver>(resolver, nameof(resolver)); return((T)resolver.GetService(typeof(T), (object)null)); }
private static DbSpatialServices GetSpatialServices( IDbDependencyResolver resolver, DbProviderInfo key, Func<DbProviderServices> providerServices) // Delegate use to avoid lookup when not needed { DebugCheck.NotNull(resolver); DebugCheck.NotNull(key); DebugCheck.NotNull(providerServices); var services = _spatialServices.GetOrAdd( key, k => resolver.GetService<DbSpatialServices>(k) ?? providerServices().GetSpatialServicesInternal(k.ProviderManifestToken, throwIfNotImplemented: false) ?? resolver.GetService<DbSpatialServices>()); if (services == null) { throw new ProviderIncompatibleException(Strings.ProviderDidNotReturnSpatialServices); } return services; }
/// <summary> /// Adds or replaces a resolver for a dependency of type <typeparamref name="TResolver" />. /// </summary> /// <remarks> /// Remember to call <see cref="ClearResolvers" /> from a <c>finally</c> block or Dispose method after using this method. /// </remarks> public static void AddResolver <TResolver>(IDbDependencyResolver resolver) { _resolvers[typeof(TResolver)] = k => resolver.GetService <TResolver>(k); }
/// <summary> /// Calls <see cref="IDbDependencyResolver.GetService" /> passing the generic type of the method as /// the type argument and null for the name argument. /// </summary> /// <typeparam name="T"> The contract type to resolve. </typeparam> /// <param name="resolver"> The resolver to use. </param> /// <returns> The resolved dependency, or null if the resolver could not resolve it. </returns> public static T GetService <T>(this IDbDependencyResolver resolver) { Check.NotNull(resolver, "resolver"); return((T)resolver.GetService(typeof(T), null)); }
public virtual object GetService(Type type, object key) { return(_resolvedDependencies.GetOrAdd( Tuple.Create(type, key), k => _underlyingResolver.GetService(type, key))); }
internal EntityCommandDefinition( DbProviderFactory storeProviderFactory, DbCommandTree commandTree, IDbDependencyResolver resolver = null, BridgeDataReaderFactory bridgeDataReaderFactory = null, ColumnMapFactory columnMapFactory = null) { DebugCheck.NotNull(storeProviderFactory); DebugCheck.NotNull(commandTree); _bridgeDataReaderFactory = bridgeDataReaderFactory ?? new BridgeDataReaderFactory(); _columnMapFactory = columnMapFactory ?? new ColumnMapFactory(); _storeProviderServices = (resolver != null ? resolver.GetService <DbProviderServices>(storeProviderFactory.GetProviderInvariantName()) : null) ?? storeProviderFactory.GetProviderServices(); try { if (DbCommandTreeKind.Query == commandTree.CommandTreeKind) { // Next compile the plan for the command tree var mappedCommandList = new List <ProviderCommandInfo>(); ColumnMap columnMap; int columnCount; PlanCompiler.Compile(commandTree, out mappedCommandList, out columnMap, out columnCount, out _entitySets); _columnMapGenerators = new IColumnMapGenerator[] { new ConstantColumnMapGenerator(columnMap, columnCount) }; // Note: we presume that the first item in the ProviderCommandInfo is the root node; Debug.Assert(mappedCommandList.Count > 0, "empty providerCommandInfo collection and no exception?"); // this shouldn't ever happen. // Then, generate the store commands from the resulting command tree(s) _mappedCommandDefinitions = new List <DbCommandDefinition>(mappedCommandList.Count); foreach (var providerCommandInfo in mappedCommandList) { var providerCommandDefinition = _storeProviderServices.CreateCommandDefinition(providerCommandInfo.CommandTree); if (null == providerCommandDefinition) { throw new ProviderIncompatibleException(Strings.ProviderReturnedNullForCreateCommandDefinition); } _mappedCommandDefinitions.Add(providerCommandDefinition); } } else { Debug.Assert( DbCommandTreeKind.Function == commandTree.CommandTreeKind, "only query and function command trees are supported"); var entityCommandTree = (DbFunctionCommandTree)commandTree; // Retrieve mapping and metadata information for the function import. var mapping = GetTargetFunctionMapping(entityCommandTree); IList <FunctionParameter> returnParameters = entityCommandTree.EdmFunction.ReturnParameters; var resultSetCount = returnParameters.Count > 1 ? returnParameters.Count : 1; _columnMapGenerators = new IColumnMapGenerator[resultSetCount]; var storeResultType = DetermineStoreResultType(mapping, 0, out _columnMapGenerators[0]); for (var i = 1; i < resultSetCount; i++) { DetermineStoreResultType(mapping, i, out _columnMapGenerators[i]); } // Copy over parameters (this happens through a more indirect route in the plan compiler, but // it happens nonetheless) var providerParameters = new List <KeyValuePair <string, TypeUsage> >(); foreach (var parameter in entityCommandTree.Parameters) { providerParameters.Add(parameter); } // Construct store command tree usage. var providerCommandTree = new DbFunctionCommandTree( entityCommandTree.MetadataWorkspace, DataSpace.SSpace, mapping.TargetFunction, storeResultType, providerParameters); var storeCommandDefinition = _storeProviderServices.CreateCommandDefinition(providerCommandTree); _mappedCommandDefinitions = new List <DbCommandDefinition>(1) { storeCommandDefinition }; var firstResultEntitySet = mapping.FunctionImport.EntitySets.FirstOrDefault(); if (firstResultEntitySet != null) { _entitySets = new Set <EntitySet>(); _entitySets.Add(mapping.FunctionImport.EntitySets.FirstOrDefault()); _entitySets.MakeReadOnly(); } } // Finally, build a list of the parameters that the resulting command should have; var parameterList = new List <EntityParameter>(); foreach (var queryParameter in commandTree.Parameters) { var parameter = CreateEntityParameterFromQueryParameter(queryParameter); parameterList.Add(parameter); } _parameters = new ReadOnlyCollection <EntityParameter>(parameterList); } catch (EntityCommandCompilationException) { // No need to re-wrap EntityCommandCompilationException throw; } catch (Exception e) { // we should not be wrapping all exceptions if (e.IsCatchableExceptionType()) { // we don't wan't folks to have to know all the various types of exceptions that can // occur, so we just rethrow a CommandDefinitionException and make whatever we caught // the inner exception of it. throw new EntityCommandCompilationException(Strings.EntityClient_CommandDefinitionPreparationFailed, e); } throw; } }
internal EntityCommandDefinition( DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver = null, BridgeDataReaderFactory bridgeDataReaderFactory = null, ColumnMapFactory columnMapFactory = null) { DebugCheck.NotNull(storeProviderFactory); DebugCheck.NotNull(commandTree); DebugCheck.NotNull(interceptionContext); _bridgeDataReaderFactory = bridgeDataReaderFactory ?? new BridgeDataReaderFactory(); _columnMapFactory = columnMapFactory ?? new ColumnMapFactory(); _storeProviderServices = (resolver != null ? resolver.GetService<DbProviderServices>(storeProviderFactory.GetProviderInvariantName()) : null) ?? storeProviderFactory.GetProviderServices(); try { if (DbCommandTreeKind.Query == commandTree.CommandTreeKind) { // Next compile the plan for the command tree var mappedCommandList = new List<ProviderCommandInfo>(); ColumnMap columnMap; int columnCount; PlanCompiler.Compile(commandTree, out mappedCommandList, out columnMap, out columnCount, out _entitySets); _columnMapGenerators = new IColumnMapGenerator[] { new ConstantColumnMapGenerator(columnMap, columnCount) }; // Note: we presume that the first item in the ProviderCommandInfo is the root node; Debug.Assert(mappedCommandList.Count > 0, "empty providerCommandInfo collection and no exception?"); // this shouldn't ever happen. // Then, generate the store commands from the resulting command tree(s) _mappedCommandDefinitions = new List<DbCommandDefinition>(mappedCommandList.Count); foreach (var providerCommandInfo in mappedCommandList) { var providerCommandDefinition = _storeProviderServices.CreateCommandDefinition( providerCommandInfo.CommandTree, interceptionContext); if (null == providerCommandDefinition) { throw new ProviderIncompatibleException(Strings.ProviderReturnedNullForCreateCommandDefinition); } _mappedCommandDefinitions.Add(providerCommandDefinition); } } else { Debug.Assert( DbCommandTreeKind.Function == commandTree.CommandTreeKind, "only query and function command trees are supported"); var entityCommandTree = (DbFunctionCommandTree)commandTree; // Retrieve mapping and metadata information for the function import. var mapping = GetTargetFunctionMapping(entityCommandTree); IList<FunctionParameter> returnParameters = entityCommandTree.EdmFunction.ReturnParameters; var resultSetCount = returnParameters.Count > 1 ? returnParameters.Count : 1; _columnMapGenerators = new IColumnMapGenerator[resultSetCount]; var storeResultType = DetermineStoreResultType(mapping, 0, out _columnMapGenerators[0]); for (var i = 1; i < resultSetCount; i++) { DetermineStoreResultType(mapping, i, out _columnMapGenerators[i]); } // Copy over parameters (this happens through a more indirect route in the plan compiler, but // it happens nonetheless) var providerParameters = new List<KeyValuePair<string, TypeUsage>>(); foreach (var parameter in entityCommandTree.Parameters) { providerParameters.Add(parameter); } // Construct store command tree usage. var providerCommandTree = new DbFunctionCommandTree( entityCommandTree.MetadataWorkspace, DataSpace.SSpace, mapping.TargetFunction, storeResultType, providerParameters); var storeCommandDefinition = _storeProviderServices.CreateCommandDefinition(providerCommandTree); _mappedCommandDefinitions = new List<DbCommandDefinition>(1) { storeCommandDefinition }; var firstResultEntitySet = mapping.FunctionImport.EntitySets.FirstOrDefault(); if (firstResultEntitySet != null) { _entitySets = new Set<EntitySet>(); _entitySets.Add(mapping.FunctionImport.EntitySets.FirstOrDefault()); _entitySets.MakeReadOnly(); } } // Finally, build a list of the parameters that the resulting command should have; var parameterList = new List<EntityParameter>(); foreach (var queryParameter in commandTree.Parameters) { var parameter = CreateEntityParameterFromQueryParameter(queryParameter); parameterList.Add(parameter); } _parameters = new ReadOnlyCollection<EntityParameter>(parameterList); } catch (EntityCommandCompilationException) { // No need to re-wrap EntityCommandCompilationException throw; } catch (Exception e) { // we should not be wrapping all exceptions if (e.IsCatchableExceptionType()) { // we don't wan't folks to have to know all the various types of exceptions that can // occur, so we just rethrow a CommandDefinitionException and make whatever we caught // the inner exception of it. throw new EntityCommandCompilationException(Strings.EntityClient_CommandDefinitionPreparationFailed, e); } throw; } }