Question

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?

Was it helpful?

Solution

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());

// ASP.NET:
var thing = new ThisUsesProvider(new DefaultProviderProvider());

This pattern is called Dependency Injection and Inversion of Control.

OTHER TIPS

Check to see if HttpContext.Current is not null:

if(HttpContext.Current!=null)
   // I'm running on a web server

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.

If you're writing a module that can be accessed from either web-based or non-web-based applications, the Right Way™ to handle the configuration, IMHO, is to have the client code tell you what environment you're in. This should be a minor imposition on client code, and greatly reduce the complexity of your code. One possible solution would be to have the client pass in an object that conforms to the same interface (though a quick glance at the MSDN docs shows there's not an interface defined for ProvidersHelper, so the easy route is out).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top