Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Interface as parameter in WCF service?

Tags:

c#

wcf

I have the following however I am not sure this is the correct way of doing it.

namespace WCFServices
{
    [ServiceContract(Name = "IService")]
    [ServiceKnownTypeAttribute(typeof(DataItem))]
    public interface IService
    {
        [OperationContract]
        void InstantiateThirdParties(string name, IEnumerable<IDataItem> data, IEnumerable<string> modules, IEnumerable<string> states);
    }
}

this is the code that uses the interface.

namespace WCFServices
{
    public class Service : IService
    {
        public void InstantiateThirdParties(string name, IEnumerable<IDataItem> data, IEnumerable<string> modules, IEnumerable<string> states)
        {
            Process.ExecuteAll(name, data, modules, states);
        }
    }
}

and my only object type at the moment is the following.

namespace DataObjects
{
    [Serializable]
    [DataContract]
    public class DataItem : IDataItem
    {
        public DataItem();

        [DataMember]
        public CustomerInfo customer { get; set; }

        [DataMember]
        public LoanInfo loan { get; set; }

        [DataMember]
        public DateTime loanProcessingDate { get; set; }

        [DataMember]
        public string moduleID { get; set; }

        [DataMember]
        public string processingState { get; set; }
    }
}

am I headed in the right direction?

like image 323
Tyler Buchanan Avatar asked Oct 19 '22 23:10

Tyler Buchanan


2 Answers

You need to use the KnownTypeAttribute instead of the ServiceKnownTypeAttribute.

like image 131
papadi Avatar answered Oct 22 '22 13:10

papadi


If the interface in question is your IDataItem which is used in the IEnumerable<IDataItem> parameter then you need to mark the interface itself as a known type:

[KnownTypeAttribute(typeof(IDataItem))]

Check this blog: http://blogs.msdn.com/b/domgreen/archive/2009/04/13/wcf-using-interfaces-in-method-signatures.aspx

Edit: Should be KnownTypeAttribute not ServiceKnownTypeAttribute as papadi pointed out correctly.

Edit 2:

namespace WCFServices
{
    [ServiceContract(Name = "IService")]
    [ServiceKnownTypeAttribute(typeof(DataItem))]
    public interface IService
    {
        [OperationContract]
        void InstantiateThirdParties(string name, IEnumerable<IDataItem> data, IEnumerable<string> modules, IEnumerable<string> states);
    }
}

namespace DataObjects
{
    [DataContract]
    [KnownType(typeof(IDataItem))]
    public class DataItem : IDataItem
    {
        ...
    }
}
like image 45
Jerrington Avatar answered Oct 22 '22 13:10

Jerrington