Windows Service不在ServiceBase.Run()

时间:2017-01-12 11:19:46

标签: c# wcf windows-services

我在Windows 10上运行的C#.NET 4.0中有一个Windows服务,我无法看到对#34; OnStart()"在我的服务中调用ServiceBase.Run()之后。该服务是一个WCF服务主机,因此我可以在IIS之外拥有一个长时间运行的WCF服务。

我已使用installutil在我的计算机上安装了该服务,并且我从MMC服务视图启动它。当我运行它时,该服务似乎正确启动,但是当我附加调试器(Visual Studio 2015社区)时,它无法比ServiceBase.Run()更进一步。

在Windows日志中,我看到该服务正确启动并在事件查看器中报告"服务已成功启动。"

我不能为我的生活弄清楚为什么它不会打电话" OnStart()"即使我在那时进行了记录,也没有任何东西能让记录器说出" OnStart()"方法被称为。

主要入口点

public static class Program
{
    private static readonly ILog Log = LogManager.GetLogger(typeof(Program));

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    public static void Main()
    {
        try
        {
            ServiceBase.Run(new MyService{ServiceName = $"{nameof(MyService)}"});
        }
        catch (Exception ex)
        {
            Log.Error(ex.ToString(), ex);
        }
    }
}

我的服务

public partial class MyService: ServiceBase
{
    private static readonly ILog Log = LogManager.GetLogger(typeof(MyService));

    private ServiceHost _wcfServiceHost;

    public MyService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        Log.Info($"{nameof(MyService)} {nameof(OnStart)}.");

        try
        {
            _wcfServiceHost?.Close();

            _wcfServiceHost= new ServiceHost(new WcfService());
            _wcfServiceHost.Open();

            Log.Info($"{nameof(MyService)} has now started a new instance of {nameof(WcfService)}");
        }
        catch (Exception ex)
        {
            Log.Error("Service host failed to start.", ex);
        }
    }

    protected override void OnStop()
    {
        Log.Info($"{nameof(MyService)} {nameof(OnStop)}.");

        if (_wcfServiceHost!= null)
        {
            _wcfServiceHost.Close();
            _wcfServiceHost= null;
        }
    }
}

根据NPhillips的评论,似乎记录器配置不正确。所以我没有看到任何错误的输出,因此附加调试器为时已晚。我已经清除了记录器错误,我现在收到以下错误。

我现在记录了以下异常。

System.InvalidOperationException: In order to use one of the ServiceHost constructors that takes a service instance, the InstanceContextMode of the service must be set to InstanceContextMode.Single.  This can be configured via the ServiceBehaviorAttribute.  Otherwise, please consider using the ServiceHost constructors that take a Type argument.
   at System.ServiceModel.ServiceBehaviorAttribute.ApplyInstancing(ServiceDescription description, ServiceHostBase serviceHostBase)
   at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
   at System.ServiceModel.ServiceHostBase.InitializeRuntime()
   at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)

0 个答案:

没有答案