WCF - Single Web Service Endpoint Using Partial Classes - c#

A project I am working on requires a structure as such:
{BasePrefix}/Application/{id}/Security/Users/{userId}
{BasePrefix}/Application/{id}/Objects/{objectId}
etc.
Application.svc would be end up being my WCF Web Service. I tried to convince them to do:
{BasePrefix}/Security/Application/{id}/Users/{userId}
This would allow me to have multiple WCF Web Services as Security.svc, Objects.svc, etc.
They still want it all under application so instead of throwing all my service methods into a single file, I wanted to break it out by functionality and use partial classes to combine it all into one resource.
I saw an article about how to do this here: http://www.meineck.net/2008/04/wcf-hosting-multiple-wcf-services-as.html
The developer in that article is working with a Net TCP binding, however, so I am not sure if this will work with a WebHttpBinding and how IIS will handle the multiple resources.
Has anyone done this? Is the article I linked a good resource? Or is there a better alternative method to achieve the same results?

The methodology in the linked article is sound, and will work for bindings other than netTcpBinding (including webHttpBinding, wsHttpBinding and so on).
However, I believe what you are trying to do is use a URL rewriting scheme (probably using the UriTemplate property), which is subtly different from what that article actually talks about. It is referring to the creation and implementation of multiple interfaces, by the same service, and mapping each interface to its own endpoint.
The approach does not work with a single endpoint. So if your endpoint is {BasePrefix}/Application, that can only be mapped to one interface (say IApplicationService) in the configuration.
In your case, I don't think you'll be able to go the multiple-interface route because you need to have just one endpoint. So you'll still need a single monolithic interface with all of the methods (ugly), but you could in theory use partial classes to split up the implementation of those methods into logical groups. It's better, but not exactly ideal.
You were on the right track with your original assessment. If your scheme looked like:
{BasePrefix}/Security/Application/{id}/Users/{userId}
{BasePrefix}/Repository/Application/{id}/Objects/{objectId}
Then you would be able to use either of the approaches - either have multiple services, or have a single service that implements multiple interfaces and hosts multiple endpoints.
What the code/configuration in that article is really designed to do is enable a single service instance to host multiple endpoints. The main reason to do this is if you would otherwise have to duplicate a lot of code between services. Unfortunately that's not your goal here, so you will either have to push harder for your proposed URI scheme, or deal with a monolithic service contract (interface) and do the best you can to keep the implementation clean through #region directives and/or partial classes.

Related

Creating an API in shared library in .NET Core

In our microservices architecture there are several APIs that are part of shared library included with each service. We want these APIs (ex. /cache/delete) to appear in all services. However, what we cannot figure out is how to dynamically assign the URL route. So what we need is the URL route base (specific to the service) would be prefixed to the resource/action. For example:
https://example.com/api/service1/cache/delete
https://example.com/api/service2/cache/delete
In C# v10 interpolated constant strings were introduced, that would allow something like [Route($"{prefix}/cache/delete)]. But we will not be on this version for a while.
I was wondering if there is another possible implementation for this.
It sounds like you have each service do its own route prefix. I'm not typically a fan of that as I just have other things do that, like the API gateway or use some sort of service discovery tool (Consul, service discovery in Kubernetes, etc.).
If you did this, you'd be able to just map to /cache and it would make life easy on both ends (the service and the library).
If you want to keep the same pattern you're currently doing, you can tap into IEndpointRouteBuilder. Each service can then use the default you set (/cache), or define their own endpoint. That's where the service can insert their own prefix and you take the responsibility off of the library for making sure it has the right endpoint.
Trying to do a catch-all generic library that deals with something like that routing, which is specific to each service is asking for trouble. You would be forcing yourself into the same routing pattern for every service you ever make that uses caching even though you may want something else. Allow the route to be flexible and managed by the service rather than coupling the two together like that.

Q: How to build the most basic service aggregation pattern?

I have a set of services I want to be able to access via one end point altogether.
Now I want to build something in wcf rather than use an existing framework/software so that is out of the question.
Suppose I have 10 contracts each representing a contract of an indepedent service that I want to "route" to, what direction should I go?
public partial class ServiceBus : ICardsService
{
//Proxy
CMSClient cards = new CMSClient();
public int methodExample()
{
return cards.methodExample();
}
So far I've tried using a partial class "ServiceBus" that implements each contract but then I have more than a few (60+) recurrences of identical function signatures so I think I should think in a different angle.
Anyone got an idea of what I should do? or what direction to research? currently I'm trying to use a normal wcf service that's going to be configured with a lot of client end points directing to each of the services it routes TO - and one endpoint for the 'application' to consume.
I'm rather new at wcf so anything that may seem too trivial to mention please do mention it anyway.
Thanks in advance.
I have a set of services I want to be able to access via one end point
altogether.
...
So far I've tried using a partial class "ServiceBus" that implements
each contract
It's questionable whether this kind of "service aggregation" pattern should be achieved by condensing multiple endpoints into an uber facade endpoint. Even when implemented well, this will still result in a brittle single failure point in your solution.
Suppose I have 10 contracts each representing a contract of an
indepedent service that I want to "route" to, what direction should I
go?
Stated broadly, your aim seems to be to decouple the caller and service so that the caller makes a call and based on the call context the call is routed the relevant services.
One approach would be to do this call mediation on the client side. This is an unusual approach but would involve creating a "service bus" assembly containing the capability to dynamically call a service at run-time, based on some kind of configurable metadata.
The client code would consume the assembly in-process, and at run-time call into the assembly, which would then make a call to the metadata store, retrieving the contract, binding, and address information for the relevant service, construct a WCF channel, and return it to the client. The client can then happily make calls against the channel and dispose it when finished.
An alternative is to do the call mediation remotely and luckily WCF does provide a routing service for this kind of thing. This allows you to achieve the service aggregation pattern you are proposing, but in a way which is fully configurable so your overall solution will be less brittle. You will still have a single failure point however, unless you load balance the router service.
I'm not sure about making it client side as I can't access some of the
applications (external apis) that are connecting to our service
Well, any solution you choose will likely involve some consumer rewrite - this is almost unavoidable.
I need to make it simple for the programmers using our api
This does not rule out a client side library approach. In fact in some ways this will make it really easy for the developers, all they will need to do is grab a nuget package, wire it up and start calling it. However I agree it's an unusual approach and would also generate a lot of work for you.
I want to implement the aggregation service with one endpoint for a
few contracts
Then you need to find a way to avoid having to implment multiple duplicate (or redundant) service operations in a single service implementation.
The simplest way would probably be to define a completely new service contract which exposes only those operations distinct to each of the services, and additionally a single instance of each of the redundant operations. Then you would need to have some internal routing logic to call the backing service operations depending on what the caller wanted to do. On second thoughts not so simple I think.
Do you have any examples of a distinct service operation and a redundant one?

Create WCF Client without auto generated proxy

looking at
WCF ChannelFactory vs generating proxy
appears that the best practice in creating a WCF client is to create a proxy (Not autogenerated).
I've been looking online for a while and i didn't find any complete example(Proxy class, web.config)
Could you provide an example or links to resources?
This article is about exactly what you're asking, I believe:
WCF the Manual Way... The Right Way
Having shared that, though, creating your proxies manually is probably not always the best possible use of your time. The article goes into some great reasons for doing so - you'll certainly have more control, your clients may have an easier time, etc. but overall, doing things manually like this will require more of your time, and explaining to users of your service exactly how to use the proxy you provide may be a pain.
There's a reason WCF allows metadata exchange and discovery and VS will auto create proxies for you.
Either way, it's a cool article and a technique well worth learning.
This is how I do it.
Get service contracts and data contracts
If I have access to the service code, I have all the contracts. If not, I can use svcutil or Add Service Reference to generate them.
Make config
I use Add Service Reference just to get the app.config file. I then delete everything else it generates. Edit the app.config as necessary.
Define factory
Say I have a service contract IFooService:
interface IFooServiceChannel : IFooService, IClientChannel { }
That is literally it. No members.
Create factory
fooServiceFactory = new ChannelFactory<IFooServiceChannel>(
"NetTcpBinding_IFooService");
The string "NetTcpBinding_IFooService" is the name attribute of the binding element in app.config.
Create channel
fooService = fooServiceFactory.CreateChannel();
Use it
fooService.DoSomething();
The trickiest part is getting app.config right. You need to learn about bindings and endpoints. It's a bit of a learning curve, but nothing drastic.
Here are the basic steps.
Create your service like normal.
Move the interface that your service implements into an assembly that can be shared with the client.
Create a ChannelFactory where T is your interface. You will have to give the uri of your service to the constructor.
Call factory.CreateChannel(). This will be type T.
Use the channel to make calls.
It is really that simple. No auto generated code, no service references. It gets a little more complicated with async calls and Silverlight, but not too much.

Abstracting out existence of service bus/distributed messaging?

I'm working on a system right now that is in a single process space; we are breaking this up into several processes, initially to run on the same box but ultimately to distribute across several separate machines. I'm leaning towards using an ESB (NServiceBus, Rhino ESB) or possibly rolling my own with WCF + queues to handle the pub/sub and request/response scenarios our app has.
However, I'm struggling with the abstraction: I don't want the various components to know they are talking over the bus. The current APIs connecting the various services translate pretty well to this kind of model, but I want to hide that from the client and server sides. Short of writing a lot of custom proxy code for the client and server, is there a better way to approach this? I realize WCF can auto-generate proxies based on the service definition, but I really like some of the other stuff I get with (say) rhino servicebus.
Ideally, I'd like to be able to swap out different implementations (with and without an ESB/messaging layer) just using IoC (knowing there would have to be limits enforced by convention on what can be passed across the interfaces), but I'm not sure where to go with that. I'd really prefer to not have to change every method call on the current interfaces into its own discrete message class, either.
Any resources/patterns/tools to help me do this? Please ask questions if I'm not clear. Thanks.
There may not be one solution/off-the-shelf component that might help you.
Problem 1:
The basic problem can be solved via an ESB, as it provides location transparency and service aggregation. A regular ESB mediates/brokers requests between service consumer and service provider.
Take a simple example:
Service_A depends on Service_B
Service_C depends on Service_B
Service_B depends on Service_D
In this scenario, the best way to progress is this:
Define contracts exposed by Service_B and Service_D as external dependencies (possibly as a web service, though an ESB supports multiple protocols) in services Service_A, Service_C and Service_B, and consume via an ESB.
In ESB, to start with, route thes services Service_B and Service_D on the same instance.
If you migrate Service_D and Service_B as Service_Dx and Service_Bx on a different location, the ESB can be reconfigured to route to the new location. Also, an ESB can be configured to route to Service_B or Service_Bx based on some set of parameters (eg., test data to Service_B and production data to Service_Bx)
Problem 2:
The problem of IOC could probably be hard to achieve; there may not be a need.
I presume the clients, instead of consuming from a known location, are injected with the whereabouts of service location. This in reality transfers the configuration to client side. With this, for every new client added to the system there needs to be a separate configuration control. This might lead to logistical issues.
Please post your final solution, very interested to know your approach.

Propagate Application Service as WCF Service

I have description of my Application Services using my fancy classes (ServiceDescription class that contains collection of ServiceMethod description, for simplification).
Now, I want to expose one Application Service as one WCF Service (one Contract). The current solution is very lame - I have console application that generates *.svc file for each Application Service (ServiceDescription). There is one method (Operation) generated for one ServiceMethod.
This works well but I would like to make it better. It could be improved using T4 template but I'm sure that there is still better way in WCF.
I would still like to have one *.svc file per one Application Service but I don't want to generate methods (for corresponding Application Service methods).
I'm sure that there must be some interfaces that allow to discover operations dynamically, at runtime. Maybe IContractBehavior...
Thanks.
EDIT1:
I don't want to use generic operation contract because I would like to have the ability to generate service proxy with all operations.
I'm sure that if I write WCF service and operations by hand then WCF uses reflection to discover the operations in the service.
Now, I would like to customize this point in order not to use reflection, just use my "operations discovering code" instead.
I think there is nothing wrong with static code generation in that case. In my opinion, it is a better solution than dynamic generation of contracts. Keep in mind that your contract is the only evidence you have/provide that a service is hosting a particular set operations.
The main issue I see about the dynamic approach is about versioning and compatibility. If everything is dynamically generated, you may end up transparently pushing breaking changes into the system and create some problems with existing clients.
If you have a code generator when you plan on implementing some changes in the application services, it will be easier to remember that the changes you make on the services may have a huge impact.
But if you really want to dynamically handle messages, you could use a generic operation contract (with the Action property set to *), and manually route the messages to the application services.
Keep in mind that you would lose the ability to generate from the service a proxy containing a list of operations available.

Categories

Resources