如何判断我是否在网络服务器下运行?
我正在编写一个 C# .NET 模块,我想使用提供程序模式。
如果我的代码在 Web 服务器上运行,我可以访问 System.Web.Configuration 并可以调用 ProvidersHelper 来加载由 Web 确定的适当提供程序.config 数据。
如果我的代码在独立环境中运行,我将无法访问此类。
在我看来,我可能会编写一个包装类,它使用反射来(a)确定我是否可以访问内置的 System.Web.Configuration.ProvidersHelper ,如果不能,(b)提供功能等效的界面,仅依赖于我在独立模式下可用的资源。
有没有人以前遇到过这个问题和/或有建议?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
检查 HttpContext.Current 是否不为 null:
Check to see if HttpContext.Current is not null:
如果您想避免对
System.Web
程序集进行引用,则必须创建一个公开您感兴趣的信息的接口,并让您的使用者酌情提供该接口的实现者:此模式称为依赖注入和控制反转。
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:This pattern is called Dependency Injection and Inversion of Control.
您可以创建一个 statis IsWeb 函数,该函数返回 HttpContext.Current 是否为 null。
如果它不为空,则您有一个网站,如果它为空,则您没有。
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.
如果您正在编写一个可以从基于网络或非基于网络的应用程序访问的模块,恕我直言,处理配置的正确方法™是让客户端代码告诉您您所处的环境。这应该是对客户端代码的较小影响,并大大降低代码的复杂性。 一种可能的解决方案是让客户端传入一个符合相同接口的对象(尽管快速浏览一下 MSDN 文档显示没有为 ProvidersHelper 定义接口,因此简单的路线已经消失)。
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).