在 WCF 自托管服务中指定单例服务 [英] Specify a Singleton service in a WCF self hosted service

查看:27
本文介绍了在 WCF 自托管服务中指定单例服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个通过 WCF 公开服务的应用程序.该服务是自托管的(控制台应用程序),需要使用 Singleton 实例.我试图弄清楚如何在服务配置中指定单例使用服务实现上的属性.是否可以在没有属性的情况下在代码中指定单例?

I am writing an application that exposes a service via WCF. The service is self-hosted (console app) and needs to use a Singleton instance. I am trying to figure out how to specify singleton in the service configuration without using attributes on the service implementation. Is it possible to specify singleton in code without an attribute?

谢谢,埃里克

推荐答案

您可以将服务的实例传递给 ServiceHost 构造函数 而不是传递类型.在这种情况下,您传递的实例将用作单例.

You can pass instance of the service to the ServiceHost constructor instead of passing a type. In such case your passed instance will be used as singleton.

我以前的解决方案不起作用.向 ServiceHost 构造函数提供实例仍然需要 ServiceBehaviorAttributeInstanceContextMode.Single.但这应该有效:

My former solution doesn't work. Providing instance to ServiceHost constructor still demands ServiceBehaviorAttribute with InstanceContextMode.Single. But this one should work:

var host = new ServiceHost(typeof(Service));
var behavior = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
behavior.InstanceContextMode = InstanceContextMode.Single;
host.Open();

ServiceBehaviorAttribute 即使您没有指定它也包含在内,因此您只需要获取它并更改默认值即可.

ServiceBehaviorAttribute is included even if you don't specify it so you just need to get it and change default value.

这篇关于在 WCF 自托管服务中指定单例服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆