Pau*_*der 82
由于它只是一个类,因此可以使用静态构造函数,该构造函数将在第一次使用Type时调用.
public Service : IContract
{
public Service(){ // regular constructor }
static Service(){ // Only called first time it's used. }
}
Run Code Online (Sandbox Code Playgroud)
您始终可以手动将global.asax文件添加到WCF服务应用程序,因为它在IIS上托管并与ASP.NET管道集成:
<%@ Application Codebehind="Global.asax.cs" Inherits="WcfApplication" Language="C#" %>
public class WcfApplication : HttpApplication
{
protected void Application_Start()
{
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,这可能有点棘手,因为调用WCF服务的首选方式是"按通话",例如你没有真正拥有任何"开始"然后只是挂起,真的.
如果您在IIS或WAS中托管服务,它甚至是服务主机的"按需加载" - 当消息到达时,主机将被实例化并处理请求.
如果你自己托管,你要么有一个控制台或Winforms应用程序 - 所以你可以在那里挂钩知道它们何时开始.如果您有一个Windows服务来托管您的服务主机,您很可能会覆盖ServiceBase类上的OnStart和OnStop方法 - >挂钩到那里.
问题更多:你究竟想要完成什么?只是记录或类似的东西,或者你想在内存中建立一些东西来坚持?
渣
小智 5
如果你有一个自托管的 WCF 服务,你可以在服务的 Opening 中添加一个事件,在这个事件中你可以分配一个静态变量,就像这篇文章:
//Static Variables in a WCF Service
public class Post2331848
{
[ServiceContract]
public interface ITest
{
[OperationContract]
string GetString();
}
public class Service : ITest
{
public static string TheString;
public string GetString()
{
return TheString;
}
}
static void host_Opening(object sender, EventArgs e)
{
Service.TheString = "This is the original string";
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
//This is the magic line!
host.Opening += new EventHandler(host_Opening);
host.Open();
Console.WriteLine("Host opened");
Console.ReadLine();
host.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
(原文来自http://www.eggheadcafe.com/community/aspnet/18/10162637/help-in-maintain-global-variable-in-wcf.aspx)
祝你好运!
归档时间: |
|
查看次数: |
49962 次 |
最近记录: |