【问题标题】:WCF Singleton-Service error: The service type provided could not be loaded as a service because it does not have a default constructorWCF Singleton-Service 错误:提供的服务类型无法作为服务加载,因为它没有默认构造函数
【发布时间】:2016-09-06 15:42:35
【问题描述】:

我在 WCF 中遇到了以下奇怪的问题,我无法找出原因:

我正在使用 WCF 来确定是否将它用于我需要为类似打印机的设备实现的远程控制 API。该设备由运行在 .Net 中实现的控制器软件的 Windows-PC 控制。对于这个软件,我需要实现 API。

该服务是从控制器软件内部自托管的,我目前正在研究如何创建 WCF 服务的单例实例,以便我可以使用来自控制器的相应对象/类创建此实例-软件。我已经使用简化版本让它工作,但奇怪的是,如果服务不包含默认(无参数)构造函数,我会收到此警告。更奇怪的是,我正在做的正是第二句话中异常告诉我的事情(或者至少我喜欢这样认为)。此异常在标题为WCF Service Host 的单独窗口中抛出,之后程序继续正常执行:

System.InvalidOperationException:提供的服务类型无法作为服务加载,因为它没有默认(无参数)构造函数。要解决此问题,请为类型添加默认构造函数,或将类型的实例传递给主机。

在 System.ServiceModel.Description.ServiceDescription.CreateImplementation(Type serviceType)

在 System.ServiceModel.Description.ServiceDescription.SetupSingleton(ServiceDescription serviceDescription, Object implementation, Boolean isWellKnown)

在 System.ServiceModel.Description.ServiceDescription.GetService(Type serviceType)

在 System.ServiceModel.ServiceHost.CreateDescription(IDictionary`2&impliedContracts)

在 System.ServiceModel.ServiceHostBase.InitializeDescription(UriSchemeKeyedCollection baseAddresses)

在 System.ServiceModel.ServiceHost..ctor(Type serviceType, Uri[] baseAddresses)

在 Microsoft.Tools.SvcHost.ServiceHostHelper.CreateServiceHost(Type type, ServiceKind kind)

在 Microsoft.Tools.SvcHost.ServiceHostHelper.OpenService(ServiceInfo info)

这是我用来创建服务的代码。我在Service.cs 中注释了注释行,其中包含默认构造函数。有趣的是,当我包含默认构造函数(因此永远不会抛出错误)时,它永远不会被调用(我通过设置断点确认了这一点)。如果您取消注释,则不会引发异常。

Server.cs:

public class Server
{
    private ServiceHost svh;
    private Service service;

    public Server()
    {
        service = new Service("A fixed ctor test value that the service should return.");
        svh = new ServiceHost(service);
    }

    public void Open(string ipAdress, string port)
    {
        svh.AddServiceEndpoint(
        typeof(IService),
        new NetTcpBinding(),
        "net.tcp://"+ ipAdress + ":" + port);
        svh.Open();
    }

    public void Close()
    {
        svh.Close();
    }
}

Service.cs:

    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant,
                 InstanceContextMode = InstanceContextMode.Single)]
public class Service : IService
{
    private string defaultString;

    public Service(string ctorTestValue)
    {
        this.defaultString = ctorTestValue;
    }

    
    //// when this constructor is uncommented, I do not get the error
    //public Service()
    //{
    //    defaultString = "Default value from the ctor without argument.";
    //}

    public string GetDefaultString()
    {
        return defaultString;
    }

    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }

    public string Ping(string name)
    {
        Console.WriteLine("SERVER - Processing Ping('{0}')", name);
        return "Hello, " + name;
    }

    static Action m_Event1 = delegate { };

    static Action m_Event2 = delegate { };

    public void SubscribeEvent1()
    {
        IMyEvents subscriber = OperationContext.Current.GetCallbackChannel<IMyEvents>();
        m_Event1 += subscriber.Event1;
    }

    public void UnsubscribeEvent1()
    {
        IMyEvents subscriber = OperationContext.Current.GetCallbackChannel<IMyEvents>();
        m_Event1 -= subscriber.Event1;
    }

    public void SubscribeEvent2()
    {
        IMyEvents subscriber = OperationContext.Current.GetCallbackChannel<IMyEvents>();
        m_Event2 += subscriber.Event2;
    }

    public void UnsubscribeEvent2()
    {
        IMyEvents subscriber = OperationContext.Current.GetCallbackChannel<IMyEvents>();
        m_Event2 -= subscriber.Event2;
    }

    public static void FireEvent1()
    {
        m_Event1();
    }

    public static void FireEvent2()
    {
        m_Event2();
    }

    public static Timer Timer1;
    public static Timer Timer2;

    public void OpenSession()
    {
        Timer1 = new Timer(1000);
        Timer1.AutoReset = true;
        Timer1.Enabled = true;
        Timer1.Elapsed += OnTimer1Elapsed;

        Timer2 = new Timer(500);
        Timer2.AutoReset = true;
        Timer2.Enabled = true;
        Timer2.Elapsed += OnTimer2Elapsed;
    }

    void OnTimer1Elapsed(object sender, ElapsedEventArgs e)
    {
        FireEvent1();
    }

    void OnTimer2Elapsed(object sender, ElapsedEventArgs e)
    {
        FireEvent2();
    }

}

IServices.cs:

    public interface IMyEvents
{
    [OperationContract(IsOneWay = true)]
    void Event1();

    [OperationContract(IsOneWay = true)]
    void Event2();
}

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract(CallbackContract = typeof(IMyEvents))]
public interface IService
{
    [OperationContract]
    string GetData(int value);

    [OperationContract]
    string GetDefaultString();

    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);

    // TODO: Add your service operations here
    [OperationContract]
    string Ping(string name);

    [OperationContract]
    void SubscribeEvent1();

    [OperationContract]
    void UnsubscribeEvent1();

    [OperationContract]
    void SubscribeEvent2();

    [OperationContract]
    void UnsubscribeEvent2();

    [OperationContract]
    void OpenSession();
}

// Use a data contract as illustrated in the sample below to add composite types to service operations.
// You can add XSD files into the project. After building the project, you can directly use the data types defined there, with the namespace "WcfService.ContractType".
[DataContract]
public class CompositeType
{
    bool boolValue = true;
    string stringValue = "Hello ";

    [DataMember]
    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }

    [DataMember]
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

Main 用于启动服务器:

static void Main(string[] args)
{
    // start server
    var server = new Server();
    server.Open("localhost", "6700");
    Console.WriteLine("Server started.");

    Console.ReadLine();
    server.Close();
}

【问题讨论】:

  • 我复制了您的代码并从我的环境中运行它,但没有出现问题。
  • 在 VS 中调试时 WcfSvcHost 是否正在运行?见msdn.microsoft.com/en-us/library/bb552363(v=vs.110).aspx
  • @KimJohnson 根据您的建议,我尝试从 VS 外部启动我的小测试程序(没有默认的无参数构造函数),但没有收到上述错误。所以我猜这可能与你的建议有关。但是,在阅读了您提供的链接后,我仍然不明白到底是什么问题。有什么进一步的建议吗?顺便说一句:我忘了在我的问题中提到:通过设置断点,我确认了 default-ctor (如果存在)永远不会被调用。谢谢和最好的问候。
  • 看起来它正在尝试托管您的代码的早期版本。清理环境,删除 bin 和 obj 文件夹。
  • @CodeCaster 感谢您的建议。我尝试删除 bin 和 obj 文件夹并执行解决方案->清理->重建。在删除 bin 文件夹时,我发现 Windows 告诉我无法删除它,因为它正在被使用。关闭 VS 后,我可以将其删除。不幸的是,错误仍然存​​在。还有什么建议吗?可能是由于某种原因它启动了两个服务或什么?奇怪....

标签: c# .net wcf


【解决方案1】:

问题是由在 Visual Studio 中调试时运行的 WcfSvcHost 引起的。据this称,“WCF Service Host枚举WCF服务项目中的服务,加载项目的配置,并为它找到的每个服务实例化一个宿主。该工具通过WCF服务模板集成到Visual Studio中并被调用当你开始调试你的项目时。”

您不需要使用 WCF 服务主机,因为您是自托管的,因此您可以通过包含该服务的项目的项目属性页面禁用它。您应该在属性页上看到“WCF 选项”选项卡。在此,关闭“调试时启动 WCF 服务主机...”选项。

【讨论】:

  • 成功了,当程序启动时,它消除了工具栏中“烦人的”WcfHostService-PopUp。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-04-18
  • 1970-01-01
  • 2019-09-20
  • 2013-07-09
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 1970-01-01
相关资源
最近更新 更多