后台 WCF 服务

WCF Services In Background

我正在尝试弄清楚如何 运行 WCF 服务作为背景 Windows 服务。

到目前为止,在我见过的所有示例中,无论是 REST-WCF Web 服务主机还是双工 WCF 服务主机,它们最终都会 运行 启动一个小型控制台 interface/service 并等待它关闭。

如何安装这些服务并让它们 运行在后台运行?

我看到这是通过普通服务完成的,它创建了一些文件:ServiceInstallerProjectInstaller.cs

TLDR;

我是这样做的,我有一个程序 class 允许我将我的应用程序作为 Windows 服务(用于生产)或作为控制台应用程序(用于调试和简单测试)

internal class Program
{
    private static void Main(string[] args)
    {
        var appMgr = new ApplicationManager();

        // pass --console and it runs as console!
        if (args.ToList().Contains("--console")) 
        {
            appMgr.Start();
            Console.Read();  // blocking here until key press
            appMgr.Stop();
        }
        else
        {
            var winService = new WinService(appMgr);
            ServiceBase.Run(winService);
        }
    }
}

我的 WinService 看起来像

public class WinService : ServiceBase
{
    private readonly ApplicationManager _appMgr;

    public WinService(ApplicationManager applicationManager)
    {
        if (applicationManager == null)
            throw new ArgumentNullException("applicationManager");

        _appMgr = applicationManager;
    }

    protected override void OnStart(string[] args)
    {
        _appMgr.Start();
    }

    protected override void OnStop()
    {
        _appMgr.Stop();
    }
}

然后我们去实现一个应用程序管理器。这会跟踪您需要的所有线程和工作人员,例如

public class ApplicationManager
{
    private WcfHost _bulkRulesWcfHost;

    public void Start()
    {
        // ...
        SetupWcf();             
    }

    public void Stop()
    {
        // ...              
        if (_bulkRulesWcfHost != null) 
            _bulkRulesWcfHost.Stop();
    }

    private void SetupWcf()
    {
        // you can have many WCF services here      
        // ...

        IBulkRules syncService = new BulkRulesService(...);
        _bulkRulesWcfHost = new WcfHost(syncService, "BulkRulesService");
        _bulkRulesWcfHost.Start();
    }
}

此时你应该想知道,什么是WcfHost

public class WcfHost
{
    private readonly ServiceHost _serviceHost;

    public WcfHost(object service, string name)
    {
        if (service == null) throw new ArgumentNullException("service");
        if (String.IsNullOrEmpty(name)) throw new ArgumentNullException("name");

        _serviceHost = new ServiceHost(service);
        Name = name;
    }

    public string Name { get; private set; }

    public void Start()
    {
        if (_serviceHost != null)
            _serviceHost.Open();
    }

    public void Stop()
    {
        if (_serviceHost != null)
            _serviceHost.Close();
    }
}

工作完成。唯一缺少的是 XML 中的配置,我将其存储在 app.config

<configuration>    
  <system.serviceModel>    
    <services>           
        ...
      </service>

    <behaviors>
      <serviceBehaviors>
        ...
      </serviceBehaviors>      
    </behaviors>

    <bindings>
      ...
    </bindings>

  </system.serviceModel>
</configuration>