简体   繁体   English

WCF Singleton-Service错误:提供的服务类型不能作为服务加载,因为它没有默认构造函数

[英]WCF Singleton-Service error: The service type provided could not be loaded as a service because it does not have a default constructor

I have the following strange issue with WCF, for which I cannot figure out the cause: 我在WCF中遇到以下奇怪的问题,无法确定原因:

I am working with WCF to figure out, whether to use it for a remote-controlling API that I need to implement for a printer-like device. 我正在与WCF合作,以确定是否将其用于需要为类似打印机的设备实现的远程控制API。 The device is controlled by a Windows-PC that runs the controller-software implemented in .Net. 该设备由Windows-PC控制,该Windows-PC运行.Net中实现的控制器软件。 It for this software that I need to implement the API. 我需要为该软件实现API。

The service is self-hosting from inside the controller-software and I am currently figuring out how I can create a singleton-instance of the WCF service, so that I can create this instance with corresponding objects/classes from withing controller-software. 该服务是从控制器软件内部自我托管的,目前我正在弄清楚如何创建WCF服务的单例实例,以便可以通过控制器软件来创建具有相应对象/类的实例。 I have gotten this to work using a reduced version, but oddly enough I am getting this warning, if the service does not include a default (parameter-less) constructor. 我已经使用简化版本使它工作了,但是奇怪的是,如果服务不包含默认(无参数)构造函数,则会收到此警告。 Even weirder, I am doing exactly, what the exception is telling me in the second sentence (or at least I like to think I am). 即使是很奇怪,我也确实在做,第二句话告诉我的异常(或者至少我想以为是)。 This exception is thrown in separate window with title WCF Service Host and the program continues to execute normally afterwards: 此异常在带有标题WCF Service Host单独窗口中引发,此后此程序继续正常执行:

System.InvalidOperationException: The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. System.InvalidOperationException:由于提供的服务类型没有默认(无参数)构造函数,因此无法作为服务加载。 To fix the problem, add a default constructor to the type, or pass an instance of the type to the host. 要解决此问题,请向类型添加默认构造函数,或将类型的实例传递给主机。

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

at System.ServiceModel.Description.ServiceDescription.SetupSingleton(ServiceDescription serviceDescription, Object implementation, Boolean isWellKnown) 在System.ServiceModel.Description.ServiceDescription.SetupSingleton(ServiceDescription serviceDescription,对象实现,布尔值isWellKnown)

at System.ServiceModel.Description.ServiceDescription.GetService(Type serviceType) 在System.ServiceModel.Description.ServiceDescription.GetService(类型serviceType)

at System.ServiceModel.ServiceHost.CreateDescription(IDictionary`2& implementedContracts) 在System.ServiceModel.ServiceHost.CreateDescription(IDictionary`2&ImplementedContracts)

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

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

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

at Microsoft.Tools.SvcHost.ServiceHostHelper.OpenService(ServiceInfo info) 在Microsoft.Tools.SvcHost.ServiceHostHelper.OpenService(ServiceInfo信息)

Here is the code that I am using to create the service. 这是我用来创建服务的代码。 I commented the commented line in Service.cs , that contains the default constructor. 我在Service.cs注释了注释行,其中包含默认构造函数。 Interestingly, when I include the default constructor (and therefore the error is never thrown) it is never called (I confirmed that by setting a breakpoint). 有趣的是,当我包含默认构造函数时(因此永远不会引发错误),它永远不会被调用(我通过设置断点来确认)。 I you uncommented it, the exception is not thrown. 如果您没有对此进行评论,则不会引发异常。

Server.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 : 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 : 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 for starting the server: Main用于启动服务器:

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

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

The problem is caused by the WcfSvcHost running while you're debugging in Visual Studio. 该问题是由在Visual Studio中调试时运行的WcfSvcHost引起的。 According to this , "WCF Service Host enumerates the services in a WCF service project, loads the project's configuration, and instantiates a host for each service that it finds. The tool is integrated into Visual Studio through the WCF Service template and is invoked when you start to debug your project." 根据 ,“WCF服务主机在一个WCF服务项目中列举的服务,加载项目的配置,并实例为发现的每个服务的主机。该工具通过WCF服务模板集成到Visual Studio和被调用时,你开始调试您的项目。”

You don't need to use the WCF Service Host since you're self-hosting, so you can disable it through the project properties page for the project containing the service. 由于您是自托管的,因此不需要使用WCF服务主机,因此可以通过包含该服务的项目的项目属性页将其禁用。 You should see a tab for "WCF Options" on the property page. 您应该在属性页上看到“ WCF选项”的选项卡。 On that, turn off the "Start WCF Service Host when debugging ..." option. 然后,关闭“调试时启动WCF服务主机...”选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 WCF 服务,作为服务属性值提供的类型……找不到 - WCF Service, the type provided as the service attribute values…could not be found 无法解决在原始IIS托管的WCF示例中的错误:找不到作为服务属性值[...]提供的类型[…] - Cannot resolve error in vanilla IIS-hosted WCF example: The type […] provided as the Service attribute value […] could not be found Service.datalist无法序列化,因为它没有无参数的构造函数 - Service.datalist cannot be serialized because it does not have a parameterless constructor Web服务方法 - 无法序列化,因为它没有无参数构造函数 - Web Service method - cannot be serialized because it does not have a parameterless constructor wcf单例服务多线程 - wcf singleton service multithreaded WCF Web服务错误:类型为“ ExampleTeste45.Web.Service.SilverlightWCF”,以 - WCF Web Service error: The type 'ExampleTeste45.Web.Service.SilverlightWCF', provided as WSCF生成的WCF服务。blue服务错误“实现类型是接口或抽象类,没有提供实现对象” - WCF service generated by WSCF.blue Service Error “implementation type is an interface or abstract class and no implementation object was provided” 什么时候将执行WCF服务中Service.svc的默认构造函数? - When Will the Default Constructor of Service.svc in a WCF Service is executed? 私有WCF服务构造函数 - private WCF service constructor 具有参数化构造函数的WCF服务 - WCF Service with parameterized constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM