在 Windows 服务启动期间运行 WCF 服务方法

编程入门 行业动态 更新时间:2024-10-24 22:23:03
本文介绍了在 Windows 服务启动期间运行 WCF 服务方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我已将 WCF 服务作为 Windows 服务运行,我需要在 Windows 服务启动时运行 WCF 服务的方法.有没有可能?

I have got WCF service running as Windows service and I need to run a method of the WCF Service when Windows Service is starting. Is it possible in any way?

[ServiceContract]
public interface IWebMonitorServiceLibrary
{
    [OperationContract]
    void TestMethod();
}

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class WebMonitorServiceLibrary : IWebMonitorServiceLibrary
{
    #region properties
    #endregion


    #region events
    #endregion


    public WebMonitorServiceLibrary()
    {
        Initialization();
    }

    private void Initialization()
    {
        /////////
    }


    public void TestMethod()
    {
        //////////
    }

}

推荐答案

你没有解释为什么你想让这个初始化代码运行,但考虑到你几乎从不想使用单实例WCF 服务,正确的方法是使用依赖注入(见 如何将值传递给 wcf 服务的构造函数?).

You don't explain why you want this initialization code to run, but given you almost never want to use a single-instance WCF service, the proper way would be to use dependency injection (see How do I pass values to the constructor on my wcf service?).

创建一个对象,在其中存储要初始化的内容,并在 Windows 服务启动时对其进行初始化:

Create an object in which you store the things you want to initialize, which you initialize on your Windows Service start:

public class SomeSettingsYouWantToInitialize
{
    public string SomeSetting { get; set; }
}

public class WindowsServiceInstance : ServiceBase
{
    protected override void OnStart(string[] args)
    {
        InitializeWcfService();
    }

    private void InitializeWcfService()
    {
        var settings = new SomeSettingsYouWantToInitialize
        {
            SomeSetting = "Foo"
        };

        _yourDependencyContainer.Register<SomeSettingsYouWantToInitialize>(settings);       
    }
}

然后(使用您使用的任何依赖注入框架),将其注入您的服务的构造函数:

Then (using whatever dependency injection framework you use), inject that into your service's constructor:

public class WebMonitorServiceLibrary
{
    public WebMonitorServiceLibrary(SomeSettingsYouWantToInitialize settings)
    {
        // do stuff with settings
    }
}

这篇关于在 Windows 服务启动期间运行 WCF 服务方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-26 19:47:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1141174.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   Windows   WCF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!