Obtaining the real DbProviderFactory instance in code

It might be your code needs to obtain the real DbProviderFactory, for example for reflection purposes. As the Interceptor's Initialize method overwrites the factory types with wrapper types, it needs a bit of extra code to obtain the real factory.

To obtain the real factory, use this pattern:

var factory = DbProviderFactories.GetFactory(factoryName); // e.g. 'System.Data.SqlCLient'
var factoryForReflection = factory;

// could be a wrapping factory, injected by a profiler. Check for IServiceProvider.
IServiceProvider factoryAsServiceProvider = factory as IServiceProvider;
if(factoryAsServiceProvider != null)
        factoryForReflection = 
            (factoryAsServiceProvider.GetService(factory.GetType()) as DbProviderFactory) ?? factory;
        // apparently during the GetService call an exception occured. 
        // We'll keep the factory from the DbProviderFactories cache. 

// use factoryForReflection for reflection purposes.

As this has to be done only once, you can cache the factory instances to avoid having to call this code for every object you want to create.