我有一个 ASP.net Web 应用程序,它的业务逻辑依赖于一个单独的 DLL 类库项目。但是,我想在 DLL 项目中使用全局 HttpApplicationState。但这似乎是一个特定于 Web 项目的实现。
当然,我可以让特定类的构造函数(或方法)将 HttpApplicationState 作为参数,但我想知道是否有更雄辩的方式来做到这一点。我意识到我正在创造一些设计问题,但我真的很想能够在我的业务逻辑中利用全局的东西。
我有一个 ASP.net Web 应用程序,它的业务逻辑依赖于一个单独的 DLL 类库项目。但是,我想在 DLL 项目中使用全局 HttpApplicationState。但这似乎是一个特定于 Web 项目的实现。
当然,我可以让特定类的构造函数(或方法)将 HttpApplicationState 作为参数,但我想知道是否有更雄辩的方式来做到这一点。我意识到我正在创造一些设计问题,但我真的很想能够在我的业务逻辑中利用全局的东西。
使用HttpContext.Current.Application
您应该能够在外部类中访问 HttpApplicationState 。
更新
但我同意 John Saunders 的观点——业务逻辑不应该知道它是从哪里调用的。
You should try to separate the concerns between the web application and the class libraries. The class libraries should have as little knowledge as possible about the fact that a web application is calling them. In particular, they should not be using Session state or Application state. In fact, they should preferably have no reference to System.Web.dll!
Have the web application pass to the class library the pieces of Application state that the class library needs. The class library should have no knowledge of the fact that the data came from Application state.
This will also make it much easier to unit test the class library, as it will be possible to call it from a unit test framework.