Using Interfaces With WCF - c#

I have Googled and read for hours now and I can't find anyone that deals with my specific scenario...
I want to use interfaces in my WCF service contracts to loosely couple the service from the classes used on each end of the wire. This will enable us to have a low-level assembly that contains just the Service and Data Contracts (just interfaces) that we can hand to a consultant. On their end of the wire they can instantiate their data classes that implement our Data Contract interface, send it over the wire to us, and our WCF service will then translate/cast/whatever that incoming data into our version of a data class that implements the same interface.
Here's an example. IDataContract contains the bare information I want to transmit over the wire. The endpoints and other WCF-specific config are all default stuff (my problems may lie in that, so I can include more of it if that's where I need to change things).
EDIT: I've included more of the code and renamed a couple classes to help it be less confusing. The Name & Namespace additions to the DataContractAttributes, as well as the two sections in the config files are new additions based on information from this blog post. If I switch to an abstract base class instead of an interface, it works. However, I'd like to get this working with an interface if possible.
Shared library (my code, shared with client authors):
public interface IDataContract
{
string MyProperty { get; set; }
}
[ServiceContract]
public interface ITestService
{
[OperationContract]
IDataContract TestSharedInterface(IDataContract clientData);
}
Client code (their's):
[DataContract(Name = "IDataContract", Namespace = "http://services.sliderhouserules.com")]
public class ClientDataClass : IDataContract
{
[DataMember]
public string MyProperty { get; set; }
}
private static void CallTestSharedInterface()
{
EndpointAddress address = new EndpointAddress("http://localhost/ServiceContractsTest.WcfService/TestService.svc");
ChannelFactory<ITestService> factory = new ChannelFactory<ITestService>("ITestService", address);
ITestService proxy = factory.CreateChannel();
((IClientChannel)proxy).Open();
IDataContract clientData = new ClientDataClass() { MyProperty = "client data" };
IDataContract serverData = proxy.TestSharedInterface(clientData);
MessageBox.Show(serverData.MyProperty);
}
Client config:
<system.runtime.serialization>
<dataContractSerializer>
<declaredTypes>
<add type="ServiceContractsTest.Contracts.DataContracts.IDataContract, ServiceContractsTest.Contracts">
<knownType type="ServiceContractsTest.WcfClient.ClientDataClass, ServiceContractsTest.WcfClient"/>
</add>
</declaredTypes>
</dataContractSerializer>
</system.runtime.serialization>
Server code (mine):
public class TestService : ITestService
{
public IDataContract TestSharedInterface(IDataContract clientData)
{
ServerDataClass convertedClientData = (ServerDataClass)clientData;
IDataContract serverData = new ServerDataClass() { MyProperty = convertedClientData.MyProperty + " + server data added" };
return serverData;
}
}
[DataContract(Name = "IDataContract", Namespace = "http://services.sliderhouserules.com")]
public class ServerDataClass : IDataContract
{
[DataMember]
public string MyProperty { get; set; }
}
Server config:
<system.runtime.serialization>
<dataContractSerializer>
<declaredTypes>
<add type="ServiceContractsTest.Contracts.DataContracts.IDataContract, ServiceContractsTest.Contracts">
<knownType type="ServiceContractsTest.WcfService.ServerDataClass, ServiceContractsTest.WcfService"/>
</add>
</declaredTypes>
</dataContractSerializer>
</system.runtime.serialization>
I am getting a serialization error on the client call complaining about known types. Am I just missing some metadata markup in that client class? I'm at a loss as to where to even know the problem even lies, as I've tried all the searches I can think of and no one seems to have dealt with this specific scenario.
Basically, I want ClientDataClass to serialize to <IDataContract><MyProperty>client data</MyProperty></IDataContract> and then be able to deserialize that into a ServerDataClass instance. This seems like it should be possible.

If your data contracts are interfaces WCF can't know what object to instantiate for an incoming request. There is no need for the class to be the same as in the service, after all the Add Service Reference reads the WSDL and generates new classes based on the type info in the WSDL.

This blog gives me the right direction to find the solution for my problem. Actually I have exactly the same scenario like sliderhouserules describes in his post.
But in my scenario I can't use any abstract or base class to inherit from. So I used a TypesHelper class to read the dataContractSerializer section by myself and pass the relevant types to the WCF service.
namespace ExampleNamespace
{
public interface IJustAInstance { }
[ServiceContract]
[ServiceKnownType("GetKnownTypes", typeof(ExampleNamespace.TypesHelper))]
public interface ICreateInstance
{
IJustAInstance CreateInstance();
}
public static class TypesHelper
{
public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
{
DataContractSerializerSection section = (DataContractSerializerSection)
ConfigurationManager.GetSection(
"system.runtime.serialization/dataContractSerializer");
if (dataContractSerializerSection != null)
{
foreach (DeclaredTypeElement item in dataContractSerializerSection.DeclaredTypes)
{
foreach (TypeElement innterItem in item.KnownTypes)
{
Type type = Type.GetType(innterItem.Type);
if (typeof(IJustAInstance).IsAssignableFrom(type ))
yield return type;
}
}
}
}
}
}

You could create a BaseContract that your ClientContract and ServerContract can provide (as property) and that you can use in the respective constructor when creating new instances of the ClientContract or ServerContract.
Then you only have to add the BaseContract to your shared lib.

Related

accessing multi endpoints web services (ASMX) best practices in c#

I have a clean architecture project that provide micro services, one of which is to access Agresso ERP web services.
https://***************/service.svc
it provide many services
https://**/service.svc?FooService/Foo
https://**/service.svc?BooService/Boo
each of which has it's own service reference(connected service), and each of which has many methods.
each call to any of the end point you need to pass credentials with it.
var fooSoapClient = new FooSoapClient();
var credentials = new WSCredentials
{
Username = "fakeuser",
Password = "fakepassword",
Client = "fakeclient",
};
var result = fooSoapClient.GetFoosAsync(Foo filter,true,
credentials );
(P.S) credential class exist in all entities
namespace Foo1NS
{
public partial class WSCredentials : object
{
public string Username {get;set;}
public string Client {get;set;}
public string Password {get;set;}
}
}
namespace Foo2NS
{
public partial class WSCredentials : object
{
public string Username {get;set;}
public string Client {get;set;}
public string Password {get;set;}
}
}
i can access all end points with no problem.
I have the following Questions:
Is there a generic solution i can follow for not to Fall in DRY?
is there a design pattern that best target this issue?
Here is what I've done in the past, it fits in well into Dependency Injection/containers if you use that as well. The key thing here is to define an single interface that all services will implement. Your code that uses this should only be using the interface.
Each class should implement an interface you define, e.g. IWebServiceOperations
public interface IWebServiceOperations
{
WebServiceOperationResult GetFooAsync(WebServiceOperationRequest request);
}
I'll leave you to figure out the classes WebServiceOperationResult/Request, they just hold your request/response variables, including credentials.
Then each webservice you need to implement is done in a separate class. You also dictate in the constructor what type of implementation this is (FooSoap1 vs FooSoap2) e.g.
public class FooSoapClient : BaseClient, IWebServiceOperations
{
public FooSoapClient() : base(Clients.FooSoap1)
public GetFooAsync(...)
{
...
}
}
public class BaseClient
{
private readonly eFooServiceType _serviceType;
public eFooServiceType ServiceType {
get{
return _serviceType;
}
}
protected BaseClient(eFooServiceType service)
{
_serviceType = service;
}
}
Now you should have a bunch of class references. Either your DI container can resolve these for you, based on the service type you want, or you could add them to a Dictionary, so if you wanted to operate against FooSoap1, you'd do...
var fooSoapClient1 = myServices[Clients.FooSoap1];
await fooSoapClient1.GetFooAsync(...)

Autofac Wcf - Inject service depending on data within SOAP Request

I have a WCF Service with the following operation contract:
[OperationContract]
Response SearchEntities(Query query);
This operation takes a request that contains a specified Entity like so:
[DataContract]
public class Query
{
[DataMember]
public string SearchTerm { get; set; }
[DataMember]
public string Entity { get; set; }
[DataMember]
public bool ExactMatch { get; set; }
}
Based on the value contained within the Entity property, one the following properties is populated within this response:
[DataContract]
public class Response
{
[DataMember]
public List<Asset> Assets { get; set; }
[DataMember]
public List<Stage> Stages { get; set; }
[DataMember]
public List<Sector> Sectors { get; set; }
}
Terrible design, I know! However. I am using Autofac.Wcf as my service factory to inject dependencies. Normally I would use a common Interface and Generics to determine a service to use based on the Entity value like so:
public interface IEntitySearch<T>
{
Response Search(Query query);
}
The above interface would have several implementations for each of the Lists within the response. Using a design pattern such as a service location I could determine which service to use (all of which inherit from IEntitySearch<T>, something like:
public IEntitySearch ResolveSearcher(Query query)
{
switch(query.Entity)
{
case "Assets":
return _container.Resolve<AssetSearch>();
case "Stages":
return _container.Resolve<StageSearch>();
default:
throw new NotSupportedException();
}
}
While this works, a more elegant solution (I believe) would be to customize the Autofac container per request for this particular operation, depending on the data contained within the request.
IE: Before the WCF pipe line sends the request to the service implementation, is it possible to examine the request data and customize how the container resolves dependencies. That way I can avoid exposing dependency resolution within my service layer.
Is this possible?
If another DI library other than Autofac has a solution for this, I will happily change our DI framework.
Thanks.
I haven't personally tried this but I think a direction you can go down is to combine:
Using OperationContext.Current to get the current request message data.
Specifying a custom IServiceImplementationDataProvider for Autofac that tells Autofac which WCF interface to host for that request.
Using a lambda registration for your service implementation to switch the backing service based on OperationContext.Current.
You can see two examples of the IServiceImplementationDataProvider by looking at the DefaultServiceImplementationProvider - the one that works in Autofac WCF hosting by default; andMultitenantServiceImplementationDataProvider, which is more about generating a proxy to enable multitenant WCF hosting.
While neither of these use OperationContext.Current to determine the actual backing service, you can build on the ideas:
Look at the Autofac.Multitenant.Wcf implementation. You may be able to use it as-is. The point of the instance data provider there is that WCF grabs on to the concrete type of the service being hosted and if you try to swap types out from under it, you get errors. The multitenant support fools WCF by creating a proxy type and your implementation type can be swapped out under the proxy. Note the MultitenantServiceImplementationDataProvider doesn't actually tie anything to a tenant or tenant ID; it's only about that proxy.
In your .svc file specify a service interface rather than any individual concrete implementation since you'll be swapping out the implementation.
Use a lambda registration to figure out your implementation.
Make sure your service is InstanceContextMode.PerCall to ensure things get swapped out on a per request basis.
The registration might look something like this:
builder.Register(ctx => {
var context = OperationContext.Current;
var type = DetermineTypeFromContext(context);
return ctx.Resolve(type);
}).As<IMyServiceInterface>();
The Autofac WCF and Autofac Multitenant section on WCF may also help.
In my opinion you're trying to move your problem just to another place. Why would making decision based on request at low-level WCF is better than switch in SearchEntities method? It's much worse ;-)
I would consider to use IEntitySearch factory/provider e.q.IEntitySearchProvider (it's not so much better but always).
public interface IEntitySearch
{
bool IsMatchQuery(Query query);
Response Search(Query query);
}
// without service locator
public class EntitySearchProvider : IEntitySearchProvider
{
private readonly IEnumerable<IEntitySearch> _searchers;
public EntitySearchProvider(IEnumerable<IEntitySearch> searchers)
{
_searchers = searchers;
}
public IEntitySearch GetSearcher(Query query)
{
// last registered
return _searchers.LastOrDefault(i=>i.IsMatchQuery(query))
?? throw new NotSupportedException();
}
}
or
public interface IEntitySearchProvider
{
IEntitySearch GetSearcher(Query query);
}
public class EntitySearchProvider : IEntitySearchProvider
{
private readonly IComponentContext _container;
public EntitySearchProvider(IComponentContext container)
{
_container = container;
}
public IEntitySearch GetSearcher(Query query)
{
switch(query.Entity)
{
case "Assets":
return _container.Resolve<AssetSearch>();
case "Stages":
return _container.Resolve<StageSearch>();
default:
throw new NotSupportedException();
}
}
}
with
public class WcfService
{
private readonly IEntitySearchProvider _provider;
public WcfService(IEntitySearchProvider provider)
{
_provider = provider;
}
public Response SearchEntities(Query query)
{
var searcher = _provider.GetSearcher(query);
return searcher.Search(query);
}
}

Using object from WCF Service in my client program

I sure I'm missing something simple and obvious here but I can't find the answer:
I have a WCF service that returns Widgets. Widgets are defined in the service.
In my client program I also define and use Widgets. The Widget definition in the client and the service are identical. The problem is that Widgets returned by the service are ServiceReference1.Widget but the client program expects MyProgram.Widget. How do I get the client program to work with the service Widgets?
On the service:
[DataContract]
public class Widget
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal Price { get; set; }
}
public class Service1
{
public async Task<IEnumerable<Widget>> GetAllWidgets()
{
await Task.Delay(Util.GetDelay(), CancellationToken.None);
return GetAllWidgets();
}
}
In the client program I also define Widgets. I call the service to get some:
public async Task<List<Widget>> GetWidgetsAsync() // expects MyProgram.Widget
{
using (ServiceReference1.Service1Client client =
new ServiceReference1.Service1Client())
{
var response = await client.GetAllProductsAsync();
return response; // gets ServiceReference1.Widget
}
}
Do I need to iterate through the response and build a duplicate set of client Widgets? Or do I define Widgets in a separate library and reference it from both client and server?
Thanks
The best way is to put the passed type (DTOs) and Service Interfaces into a shared library and reference it in both projects.
I'm also guessing you are autogenerating the client based on the service layer. Don't do this for the shared DLL scenario. See this article:
http://blog.walteralmeida.com/2010/08/wcf-tips-and-tricks-share-types-between-server-and-client.html

The channeldispatcher is unable to open its ichannellistener

I am starting out with WCF. I have created two console apps (server and client) that work without any issues but since moving them onto forms I'm having all kinds of problems. I had a look here and elsewhere on the net, I can't seem to find anything that can help me with my issue. I honestly don't understand the issue but I think it may have something to do with my datatypes (they're under different namespaces)?
Here's my Server code:
public partial class Form1 : Form
{
ModelDataServer Server;
public ScraperForm()
{
InitializeComponent();
Server = new ModelDataServer(); // Opened Here
Server.Scraper = this;
}
}
[ServiceContract]
public interface IModelData
{
[OperationContract]
ArrayList GetData();
}
[ServiceBehavior(UseSynchronizationContext=false)]
public class ModelDataServer : IModelData
{
ServiceHost Host;
public DataModel Model { private get; set; }
public ModelDataServer()
{
Host = new ServiceHost(typeof (ModelDataServer),
new Uri[]
{
new Uri("http://localhost:8000")
});
Host.AddServiceEndpoint(typeof(IModelData),
new BasicHttpBinding(),
"ModelData");
Host.Open(); // Error Points Here!!!
}
public ArrayList GetData()
{
return Model.GetData();
}
public void CloseServer()
{
Host.Close();
}
}
Here's my Client code:
[ServiceContract]
public interface IModelData
{
[OperationContract]
ArrayList GetData();
}
[ServiceBehavior(UseSynchronizationContext = false)]
public class ModelDataClient
{
ChannelFactory<IModelData> HttpFactory;
IModelData HttpProxy;
public ModelDataClient()
{
HttpFactory = new ChannelFactory<IModelData>(
new BasicHttpBinding(),
new EndpointAddress("http://localhost:8000/ModelData"));
HttpProxy = HttpFactory.CreateChannel();
}
public ArrayList GetData()
{
return HttpProxy.GetData();
}
}
Here's the error I'm recieving (points to where I'm opening the ServiceHost):
The ChannelDispatcher at 'http://localhost:8000/ModelData' with contract(s) '"IModelData"' is unable to open its IChannelListener.
P.S. I have been struggling to get delegates to work outside of something I've done in a tutorial. If anyone can suggest a better way that uses delegates instead of passing my form class into the other class that would be great.
Yes, this is most likely related to namespace issues. For illustration issues, let's assume your server project's namespace is ServerApp, and your client's namespace is ClientApp. You define IModelData in both applications, which means you have ServerApp.IModelData and ClientApp.IModelData. Even though the code is identical, these are two separate interfaces (because of the namespace).
So you're trying to pass ClientApp.IModelData to the service, and it's expecting ServerApp.IModelData.
You can solve this by moving the interface IModelData to its own assembly and having the server app and the client app both reference this third assembly. That's what we do at work - all of our service contracts are in a separate assembly (two, actually, but that's a different story).
A couple of other things to note:
Unless your client is also hosting a service, you can remove the [ServiceContract] attribute from the class. Clients don't need that.
In your server app, what is Server.Scraper = this; for? It appears to be assigning the Form to a property Scraper in the service, but I don't see that property in your code. Additionally, services don't really use properties (I think I saw somewhere that you could do it, but it wasn't intuitive). I don't think you'd want to assign the entire form to the service, as service's in and of themselves don't usually have UIs - they supply data and receive data from the service.

why my WCF client gets empty result?

I am using VSTS 2008 + .Net + C# 3.5 to develop WCF service (self-hosted as a Windows Service). From client side, I am using ChannelFactory to connect to WCF service. My confusion is, when I change client side code from "public string response" to "public string responseAliasName", the value of responseAliasName is null. But when change back to variable name response, the response value is correct (value is "hi WCF").
My confusion is, I think variable name should not matter as long as the layout is the same from client and server side. Any ideas what is wrong?
Server side code:
namespace Foo
{
// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
[ServiceContract]
public interface IFoo
{
[OperationContract]
FooResponse Submit(string request);
}
[DataContract]
public class FooResponse
{
[DataMember]
public string response;
}
}
namespace Foo
{
// NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
public class FooImpl : IFoo
{
public FooResponse Submit(string request)
{
FooResponse foo = new FooResponse();
foo.response = "hi WCF";
return foo;
}
}
}
Client side code:
namespace Foo
{
// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
[ServiceContract]
public interface IFoo
{
[OperationContract]
FooResponse Submit(string request);
}
[DataContract]
public class FooResponse
{
[DataMember]
// public string responseAliasName;
public string response;
}
}
namespace FooTestClient1
{
class Program
{
static void Main(string[] args)
{
ChannelFactory<IFoo> factory = new ChannelFactory<IFoo>(
"IFoo");
IFoo f = factory.CreateChannel();
FooResponse response = f.Submit("Hi!");
return;
}
}
}
you can use
[DataContract(Name="ResponseAliasName")]
public string response;
on Server side and it will work as you expect, DataContract by default uses field or property name to serialize data, and the server can't find correct data
No, the member name is included in the serialization. If you change it on the client side, it can't deserialize back into that member.
George, why not just use "Add Service Reference" to create your client? As you can see, it's dangerous to create the client-side service contracts by hand.
My confusion is, when
I change client side code from "public
string response" to "public string
responseAliasName", the value of
responseAliasName is null. But when
change back to variable name response,
the response value is correct (value
is "hi WCF").
My confusion is, I think variable name
should not matter as long as the
layout is the same from client and
server side. Any ideas what is wrong?
The variable name that you use locally in your client is totally irrelevant - the server knows nothing about that. Given your code snippet from the client:
ChannelFactory<IFoo> factory = new ChannelFactory<IFoo>("IFoo");
IFoo f = factory.CreateChannel();
FooResponse response = f.Submit("Hi!");
This will work - no problem:
FooResponse myResponseVar1 = f.Submit("Hi!");
and so will this:
FooResponse someReallyCleverVariableNameWhateverItMightBe = f.Submit("Hi!");
But the DataContract of course is a shared element that the service and client have to agree on! You cannot locally change the names of the elements in the data contract - after all, that's what really describes how your calls are going to be turned into an XML message, and these bits and pieces have to stay in sync between the server and the client in order for the client to be able to turn the message received from the server back into an object for you to use.
The ServiceContract and the DataContract must be the same on both ends - that's the basic requirement, otherwise, pretty much nothing goes at all.
Marc

Categories

Resources