自托管 WCF ServiceHost 对象生命周期
为了启动我的 WCF 服务,我使用以下命令:
selfHost = new ServiceHost(typeof(MyServiceClass));
selfHost.Open();
在某个时刻,这将创建一个 MyServiceClass
实例。它将创建单个实例还是每个请求一个实例?
To kick off my WCF service, I use the following:
selfHost = new ServiceHost(typeof(MyServiceClass));
selfHost.Open();
At some point this will create an instance of MyServiceClass
. Will it create a single instance or an instance per request?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想将其限制为单个实例,您可以在外部实例化您的服务类并将该实例传递到服务主机中:
If you want to restrict it to a single instance you can instantiate your service class outside and the pass the instance into the servicehost:
默认情况下,它是每个请求一个实例,但您可以更改它。例如,您可以编写自己的 IInstanceProvider 和自己管理服务阶层的生活。
By default it's an instance per request but you could change this. For example you could write your own IInstanceProvider and manage the life of the service class yourself.
所有这些答案都是正确的,但它们似乎比您所问的更复杂。是否为每个调用、每个会话或单例创建实例的基本知识由 InstanceContextMode 这是您的服务类的一个属性。从那里开始阅读。
All these answers are correct, but they seem more complex than what you are asking. The basics of whether it creates an instance per call, per session, or singleton are controlled by the InstanceContextMode which is an attribute on your service class. Start reading there.
它将根据请求创建实例。如果您想要单个实例,您可以使用静态类。静态类在应用程序的整个生命周期中都存在。每次有调用或建立新的 WCF 连接时,它们不会被重新实例化。
It will create instance per request. If you want a single instance you could use a static class. Static class exists for the lifetime of the application. They don't get reinstantiated every time there is a call or new WCF connection is made.