I'm writing a C# .NET module and I would like to use the provider pattern.

If my code is running on a web server, I have access to System.Web.Configuration and can call ProvidersHelper to load an appropriate provider as determined by the web.config data.

If my code is running in a stand-alone environment, I won't have access to this class.

It seems to me that I might write a wrapper class that uses reflection to (a) determine if I can get to the built in System.Web.Configuration.ProvidersHelper, and if not, (b) provide a functionally equivalent interface that would rely only on the resources I have available in the stand-alone mode.

Has anyone out there come across this issue before and/or have suggestions?

+3  A: 

Check to see if HttpContext.Current is not null:

   // I'm running on a web server
Thanks, but unfortunately, I also don't have access to System.Web if I'm running in stand-alone mode, so I wouldn't be able to compile that code.My problem would be moot if MS had put the ProvidersHelper into a non Web class.
Given that your project would have a reference to System.Web (or it wouldn't compile), you *should* have access to System.Web.
R. Bemrose
In response to R.Bemrose, the code is used in two different assemblies, only one of which is a web server. One project has a ref to System.Web, while the other doesn't need one (except for this dependency.)

You can create a statis IsWeb function which returns whether or not HttpContext.Current is null.

If it's not null you've got a website, if it's null, you don't.

Harper Shelby
yes, that's one of those things where you'd like to say to Microsoft, "Why didn't you put the ProvidersHelper (or at least the I/F for it) in System.Configuration?" Perhaps they'll move it there one day soon.

If you want to avoid the reference on the System.Web assembly, you'll have to create an interface which exposes the information you're interested in and get your consumers to provide implementors of this interface as appropriate:

// Core assembly, doesn't reference System.Web
public class ThisUsesProviders {
    public ThisUsesProviders(IProviderProvider pp) { ... }

public interface IProviderProvider {
   SpecialProvider InstantiateSpecialProvider(/* custom arguments */);

// Helper assembly, references System.Web
public class DefaultProviderProvider : IProviderProvider
    SpecialProvider InstantiateSpecialProvider(/* custom arguments */)
        // call ProvidersHelper 

// standalone consumer:
var thing = new ThisUsesProvider(new NonStandardProvider());

var thing = new ThisUsesProvider(new DefaultProviderProvider());

This pattern is called Dependency Injection and Inversion of Control.

David Schmitt
Thanks David. I think this is just what I'm looking for! -- SL.