I've a situation where I need to call a third party service to fetch some information. Those service could be different for different clients. I've a authenticate function in my Interface as follows.
interface IServiceProvider {
bool Authenticate(string username, string password);
}
class ABCServiceProvider : IserviceProvider
{
bool Authenticate(string username, string password) { // implementation}
}
class EFGServiceProvider : IserviceProvider
{
bool Authenticate(string username, string password) { // implementation}
}
and so on... now I've came across a service provider (let's say XYZServiceProvider) that needs some additional information (agentid) for authentication. something like this...
class XYZServiceProvider
{
bool Authenticate(string username, string password, int agentid) { // implementation}
}
Now if I provide another function for Authenticate in my interface with 3 parameters, and throw not implemented exception in all the classes except for XYZServiceProvider, wouldn't it violate Interface segregation principle? I've similar situation in some of my other part of the code aswell. Can anyone please tell me whats the best way to implement this type of scenrio? I would be really very thankful.
The best way to solve this would probably be to require agentId in the interface, and to simply ignore it in the cases of ABC and DEF where they don't need it. That way, the consuming class still wouldn't know the difference.
Actually it's the Liskov Substitution Principle that is most important if the ABC, DEF and XYZ providers are to be used interchangeably; "Given a class A that is depended upon by class X, X should be able to use a class B derived from A without knowing the difference".
The Interface Segregation Principle basically says that an interface should not contain members that any of its consumers do not need, because if the definition of those members were to change, classes that don't even use that method would have to be recompiled because the interface they depended on has changed. While this is relevant (you do have to recompile all consumers of IServiceProvider if you add an overload), you will have to do that anyway if you change Authenticate()'s signature, and of more pressing concern from a maintenance standpoint is that if you added an overload of Authenticate(), your consumers now have to know which overload they need to use. That requires your consuming classes to know the difference between implementations of a common interface, violating LSP. It's never a problem providing more information than a particular provider needs, but there would be a problem using XYZ from a usage that only provides two inputs. To avoid those problems, you would always use the three-parameter overload, so why have the two-parameter one at all?
Now, if current usages of IServiceProvider are in areas that don't have and don't care about agentId, and therefore it would be difficult to begin providing it, then I would recommend an Adapter that the concrete XYZ provider plugs into, that implements your current IServiceProvider, and makes the new provider work like the old ones by providing the agentId through some other means:
public class XYZAdapter: IServiceProvider
{
private readonly XYZServiceProvider xyzProvider;
public XYZAdapter(XYZServiceProvider provider)
{
xyzProvider = provider;
}
public void Authenticate(string username, string password)
{
xyzProvider.Authenticate(username, password, GetAgentId());
}
public int GetAgentId()
{
//Retrieve the proper agent Id. It can be provided from the class creator,
//retrieved from a known constant data source, or pulled from some factory
//method provided from this class's creator. Any way you slice it, consumers
//of this class cannot know that this information is needed.
}
}
If this is feasible, it meets both LSP and ISP; the interface doesn't have to change to support LSP, therefore preventing the scenario (recompiling and redistributing dependencies) that ISP generally tries to avoid. However it increases class count, and forces new functionality in the Adapter to correctly get the needed agentId without its dependent having to provide anything it wouldn't know about through the IServiceProvider interface.
Related
I have class named User, it has fields like username, password, firstName... . is it good to place authenticate(username, password) method in it?
Ideally no, that should be the job of the controller. User class should be just a data class, which is used by the controller (the business logic class) to evaluate things like Authenticate etc.
Explanation:
You need to modularize your code(break it into components) and each component should be an independent entity but requires other components to give the whole picture of the system.
It appears by your question that you want to perform some business layer operation in your DO(data object) class. It can be done but is never recommended as it kills the idea of separation of concerns.
As for controllers, you could do something like
Have object/entity level managers, i.e, for every entity you have a manager to handle its business logic stuff. Say for a User class you have a UserManager.
Have conceptual level controllers. This means that you have controllers that handle a specific module of your system(an entire concept). For example, if you have a website that needs to authenticate users, you can have an AuthenticationController.
Now, Authentication must not necessarily map to just one table/object, though it appears that its sole target is(logically) your User table/class etc, it could be doing other stuff and accessing other entities(depending on the requirement) etc. So by having entity level managers that are used by conceptual level controllers, you could ease your development.
I would say no. Better is to have a Connection and create a user using login method with username and password:
class Connection{
public:
Connection(string connectionString);
User login(string userName, string Password);
};
That would break the MVC (Model View Controller) structure. It is best to keep these three separated for code elegance, readability, and maintainability. A quick example would be, in Java:
Model:
public class User {
private String username;
private String password;
(...)
}
Controller:
import yourmodelpackage;
public class MyController {
public static boolean authenticate(String username, String password) {
//your logic
}
}
View:
//call your authenticate() method through the controller
MyController control = new MyController();
boolean b = control.authenticate(username, password);
There are a few design patterns that maximize the use of inheritance for this structure. I'd recommend looking into the Decorator Design Pattern.
You could have a method hasPassword(string password) on the User class, if you absolutely wanted to encapsulate the verification in that class.
Can you give any good explanation what is the difference between Proxy and Decorator?
The main difference I see is that when we assume that Proxy uses composition and Decorator uses aggregation then it seems to be clear that by using multiple (one or more) Decorators you can modify/ add functionalities to pre-existing instance (decorate), whereas Proxy has own inner instance of proxied class and delegates to it adding some additional features (proxy behaviour).
The question is - Does Proxy created with aggregation is still Proxy or rather Decorator? Is it allowed (by definition in GoF patterns) to create Proxy with aggregation?
The real difference is not ownership (composition versus aggregation), but rather type-information.
A Decorator is always passed its delegatee. A Proxy might create it himself, or he might have it injected.
But a Proxy always knows the (more) specific type of the delegatee. In other words, the Proxy and its delegatee will have the same base type, but the Proxy points to some derived type. A Decorator points to its own base type. Thus, the difference is in compile-time information about the type of the delegatee.
In a dynamic language, if the delegatee is injected and happens to have the same interface, then there is no difference.
The answer to your question is "Yes".
Decorator Pattern focuses on dynamically adding functions to an object, while Proxy Pattern focuses on controlling access to an object.
EDIT:-
Relationship between a Proxy and the real subject is typically set at compile time, Proxy instantiates it in some way, whereas Decorator is assigned to the subject at runtime, knowing only subject's interface.
Here is the direct quote from the GoF (page 216).
Although decorators can have similar implementations as proxies, decorators have a different purpose. A decorator adds one or more responsibilities to an object, whereas a proxy controls access to an object.
Proxies vary in the degree to which they are implemented like a decorator. A
protection proxy might be implemented exactly like a decorator. On the other
hand, a remote proxy will not contain a direct reference to its real subject but only
an indirect reference, such as "host ID and local address on host." A virtual proxy
will start off with an indirect reference such as a file name but will eventually
obtain and use a direct reference.
Popular answers indicate that a Proxy knows the concrete type of its delegate. From this quote we can see that is not always true.
The difference between Proxy and Decorator according to the GoF is that Proxy restricts the client. Decorator does not. Proxy may restrict what a client does by controlling access to functionality; or it may restrict what a client knows by performing actions that are invisible and unknown to the client. Decorator does the opposite: it enhances what its delegate does in a way that is visible to clients.
We might say that Proxy is a black box while Decorator is a white box.
The composition relationship between wrapper and delegate is the wrong relationship to focus on when contrasting Proxy with Decorator, because composition is the feature these two patterns have in common. The relationship between wrapper and client is what differentiates these two patterns.
Decorator informs and empowers its client.
Proxy restricts and disempowers its client.
Decorator get reference for decorated object (usually through constructor) while Proxy responsible to do that by himself.
Proxy may not instantiate wrapping object at all (like this do ORMs to prevent unnecessary access to DB if object fields/getters are not used) while Decorator always hold link to actual wrapped instance.
Proxy usually used by frameworks to add security or caching/lazing and constructed by framework (not by regular developer itself).
Decorator usually used to add new behavior to old or legacy classes by developer itself based on interface rather then actual class (so it work on wide range of interface instances, Proxy is around concrete class).
Key differences:
Proxy provides the same interface. Decorator provides an enhanced interface.
Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests.
Decorator can be viewed as a degenerate Composite with only one component. However, a Decorator adds additional responsibilities - it isn't intended for object aggregation.
Decorator supports recursive composition
The Decorator class declares a composition relationship to the LCD (Lowest Class Denominator) interface, and this data member is initialized in its constructor.
Use Proxy for lazy initialization, performance improvement by caching the object and controlling access to the client/caller
Sourcemaking article quotes the similarities and differences in excellent way.
Related SE questions/links:
When to Use the Decorator Pattern?
What is the exact difference between Adapter and Proxy patterns?
Proxy and Decorator differ in purpose and where they focus on the internal implementation. Proxy is for using a remote, cross process, or cross-network object as if it were a local object. Decorator is for adding new behavior to the original interface.
While both patterns are similar in structure, the bulk of the complexity of Proxy lies in ensuring proper communications with the source object. Decorator, on the other hand, focuses on the implementation of the added behavior.
Took a while to figure out this answer and what it really means. A few examples should make it more clear.
Proxy first:
public interface Authorization {
String getToken();
}
And :
// goes to the DB and gets a token for example
public class DBAuthorization implements Authorization {
#Override
public String getToken() {
return "DB-Token";
}
}
And there is a caller of this Authorization, a pretty dumb one:
class Caller {
void authenticatedUserAction(Authorization authorization) {
System.out.println("doing some action with : " + authorization.getToken());
}
}
Nothing un-usual so far, right? Obtain a token from a certain service, use that token. Now comes one more requirement to the picture, add logging: meaning log the token every time. It's simple for this case, just create a Proxy:
public class LoggingDBAuthorization implements Authorization {
private final DBAuthorization dbAuthorization = new DBAuthorization();
#Override
public String getToken() {
String token = dbAuthorization.getToken();
System.out.println("Got token : " + token);
return token;
}
}
How would we use that?
public static void main(String[] args) {
LoggingDBAuthorization loggingDBAuthorization = new LoggingDBAuthorization();
Caller caller = new Caller();
caller.authenticatedUserAction(loggingDBAuthorization);
}
Notice that LoggingDBAuthorization holds an instance of DBAuthorization. Both LoggingDBAuthorization and DBAuthorization implement Authorization.
A proxy will hold some concrete implementation (DBAuthorization) of the base interface (Authorization). In other words a Proxy knows exactly what is being proxied.
Decorator:
It starts pretty much the same as Proxy, with an interface:
public interface JobSeeker {
int interviewScore();
}
and an implementation of it:
class Newbie implements JobSeeker {
#Override
public int interviewScore() {
return 10;
}
}
And now we want to add a more experienced candidate, that adds it's interview score plus the one from another JobSeeker:
#RequiredArgsConstructor
public class TwoYearsInTheIndustry implements JobSeeker {
private final JobSeeker jobSeeker;
#Override
public int interviewScore() {
return jobSeeker.interviewScore() + 20;
}
}
Notice how I said that plus the one from another JobSeeker, not Newbie. A Decorator does not know exactly what it is decorating, it knows just the contract of that decorated instance (it knows about JobSeeker). Take note here that this is unlike a Proxy; that, in contrast, knows exactly what it is decorating.
You might question if there is actually any difference between the two design patterns in this case? What if we tried to write the Decorator as a Proxy?
public class TwoYearsInTheIndustry implements JobSeeker {
private final Newbie newbie = new Newbie();
#Override
public int interviewScore() {
return newbie.interviewScore() + 20;
}
}
This is definitely an option and highlights how close these patterns are; they are still intended for different scenarios as explained in the other answers.
A Decorator adds extra responsibility to an object, while a proxy controls access to an object, they both use composition. If your wrapper class messes with the subject, it is obviously a proxy. Let me explain by a code example in PHP:
Code Example
Given is the following CarRepository:
interface CarRepositoryInterface
{
public function getById(int $id) : Car
}
class CarRepository implements CarRepositoryInterface
{
public function getById(int $id) : Car
{
sleep(3); //... fake some heavy db call
$car = new Car;
$car->setId($id);
$car->setName("Mercedes Benz");
return $car;
}
}
CarRepository-Proxy
A Proxy is often used as lazy loading or a cache proxy:
class CarRepositoryCacheProxy implements CarRepositoryInterface
{
private $carRepository;
private function getSubject() : CarRepositoryInterface
{
if($this->carRepository == null) {
$this->carRepository = new CarRepository();
}
return $this->carRepository;
}
/**
* This method controls the access to the subject
* based on if there is cache available
*/
public function getById(int $id) : Car
{
if($this->hasCache(__METHOD__)) {
return unserialize($this->getCache(__METHOD__));
}
$response = $this->getSubject()->getById($id);
$this->writeCache(__METHOD__, serialize($response));
return $response;
}
private function hasCache(string $key) : bool
{
//... implementation
}
private function getCache(string $key) : string
{
//... implementation
}
private function writeCache(string $key, string $result) : string
{
//... implementation
}
}
CarRepository-Decorator
A Decorator can be used as long as the added behavior does not "control" the subject:
class CarRepositoryEventManagerDecorator implements CarRepositoryInterface
{
private $subject, $eventManager;
/**
* Subjects in decorators are often passed in the constructor,
* where a proxy often takes control over the invocation behavior
* somewhere else
*/
public function __construct(CarRepositoryInterface $subject, EventManager $eventManager)
{
$this->subject = $subject;
$this->eventManager = $eventManager;
}
public function getById(int $id) : Car
{
$this->eventManager->trigger("pre.getById");
//this method takes no control over the subject
$result = $this->subject->getById($id);
$this->eventManager->trigger("post.getById");
return $result;
}
}
Proxy provides the same interface to the wrapped object, Decorator provides it with an enhanced interface, and Proxy usually manages the life cycle of its service object on its own, whereas the composition of Decorators is always controlled by the client.
Let me explain the patterns first and then come to you questions.
From the class diagram and meanings, they are very similar:
Both have the same interface as its delegatee has.
Both add/enhance the behavior of its delegatee.
Both ask the delegatee to perform operations(Should not work with null delegatee).
But they have some difference:
Different intents:
Proxy enhances the behavior of delegatee(passed object) with quite different domain knowledge from its delegatee. Eg, a security proxy adds security control of the delegatee. A proxy to send remote message needs to serialize/deserialize data and has knowlege on network interfacing, but has nothing to do with how to prepare source data.
Decorator helps on the same problem domain the delegatee works on. Eg, BufferedInputStreaman(an IO decorator) works on input, which is the same problem domain(IO) as its delegatee, but it cannot perform without a delegatee which provides IO data.
Dependency is strong or not:
Decorator relies on delegate to finish the behavior, and it cannot finish the behavior without delegatee(Strong). Thus we always use aggration over composition.
Proxy can perform faked behavior even it does not need a delegatee(Weak). Eg, mockito(unit test framework) could mock/spy a behavior just with its interface. Thus we use composition to indicate there's no strong dependency on real object.
Enhance multipletimes(as mentioned in question):
Proxy: we could utilize proxy to wrap real object once not several times.
Decorator: A decorator can wrap the real object several times or can wrap the object which is already wrapped by a decorator(which could be both a different decorator or the same decorator). Eg, for an order system, you can do discount with decorators.
PercentageDiscountDecorator is to cut 50% off, and DeductionAmountDiscountDecorator is to deduct 5$ directly if the amount is greater than 10$(). So,
1). When you want to cut 50% off and deduct 5$, you can do: new DeductionAmountDiscountDecorator(new PercentageDiscountDecorator(delegatee))
2). When you want to deduct 10$, you can do new DeductionAmountDiscountDecorator(new DeductionAmountDiscountDecorator(delegatee)).
The answer to the question has nothing to do with the difference between Proxy and Decorator. Why?
Design patterns just patterns for people who are not good at OO skills to make use of OO solutions. If you are familiar with OO, you don't need to know how many design patterns there(Before design patterns invented, with the same prolbem skilled people could figure out the same solution).
No two leaves are exactly the same, so as the problems you encount. People will always find their problems are different from the problems given by design patterns.
If your specified problem is really different from both problems that Proxy and Decorator work on, and really needs an aggregation, why not to use? I think to apply OO to your problem is much more important than you label it a Proxy or Decorator.
Following advices from people on the internet about service references, I got rid of them now and split the service/data contracts into a common assembly accesible by both the server and the client. Overall this seems to work really well.
However I’m running into problems when trying to use custom objects, or rather custom subtypes, in the service. Initially I wanted to define only interfaces in the common assembly as the contract for the data. I quickly learned that this won’t work though because the client needs a concrete class to instantiate objects when receiving objects from the service. So instead I used a simple class instead, basically like this:
// (defined in the common assembly)
public class TestObject
{
public string Value { get; set; }
}
Then in the service contract (interface), I have a method that returns such an object.
Now if I simply create such an object in the service implementation and return it, it works just fine. However I want to define a subtype of it in the service (or the underlying business logic), that defines a few more things (for example methods for database access, or just some methods that work on the objects).
So for simplicity, the subtype looks like this:
// (defined on the server)
public class DbTestObject : TestObject
{
public string Value { get; set; }
public DbTestObject(string val)
{
Value = val;
}
}
And in the service, instead of creating a TestObject, I create the subtype and return it:
public TestObject GetTestObject()
{
return new DbTestObject("foobar");
}
If I run this now, and make the client call GetTestObject, then I immediately get a CommunicationException with the following error text: “The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:09:59.9380000'.”
I already found out, that the reason for this is that the client does not know how to deserialize the DbTestObject. One solution would be to declare the base type with the KnownTypeAttribute to make it know about the subtype. But that would require the subtype to be moved into the common assembly, which is of course something I want to avoid, as I want the logic separated from the client.
Is there a way to tell the client to only use the TestObject type for deserialization; or would the solution for this be to use data transfer objects anyway?
As #Sixto Saez has pointed out, inheritance and WCF don't tend to go together very well. The reason is that inheritance belongs very much to the OO world and not the messaging passing world.
Having said that, if you are in control of both ends of the service, KnownType permits you to escape the constraints of message passing and leverage the benefits of inheritance. To avoid taking the dependency you can utilise the ability of the KnownTypeAttribute to take a method name, rather than a type parameter. This allows you to dynamically specify the known types at run time.
E.g.
[KnownType("GetKnownTestObjects")]
[DataContract]
public class TestObject
{
[DataMember]
public string Value { get; set; }
public static IEnumerable<Type> GetKnownTestObjects()
{
return Registry.GetKnown<TestObject>();
}
}
Using this technique, you can effectively invert the dependency.
Registry is a simple class that allows other assemblies to register types at run-time as being subtypes of the specified base class. This task can be performed when the application bootstraps itself and if you wish can be done, for instance, by reflecting across the types in the assembly(ies) containing your subtypes.
This achieves your goal of allowing subtypes to be handled correctly without the TestObject assembly needing to take a reference on the subtype assembly(ies).
I have used this technique successfully in 'closed loop' applications where both the client and server are controlled. You should note that this technique is a little slower because calls to your GetKnownTestObjects method have to be made repeatedly at both ends while serialising/deserialising. However, if you're prepared to live with this slight downside it is a fairly clean way of providing generic web services using WCF. It also eliminates the need for all those 'KnownTypeAttributes' specifying actual types.
I am looking for some best practices on how to handle the following scenario - flowing permissions from WCF service layer through to UI:
I have WCF services with methods that have been decorated with the PrincipalPermission attribute. I would like a means to allow a client to check if they have the required permissions before invoking the method.
A basic example of this could be checking whether a user can perform a specific function (say submitting an order), which can then be used to enable/disable a button within the UI.
Possible options are to add "chatty" operations like bool CanSubmitOrder() to the service, or instead have a single method OrderServicePermissions GetPermissions() which returns a message with a property CanSubmitOrder? I can then set the enabled state of a "Submit Order" button to the result.
So does anybody know of a better approach, or even a best practice?
Thanks in advance!
The whole point of having PrincipalPermission attributes on your service calls is that you don't have to check ahead of time whether or not the caller has the rights to call - if he doesn't, the WCF runtime will throw an exception.
Why not just rely on this built-in mechanism? Why not just put your service calls in a try..catch block and handle the exceptions if they do actually occur? It should be the "exceptional" case anyway, right?
I don't see any other "magic" way besides what you described. But the generally accepted practice would be to call and handle any exceptions if they occur.
Marc
Well, if you are able to evolve your applications to use Windows Identity Foundation (WIF) to secure your services you could achieve this using the DisplayToken property of the RequestSecurityTokenResponse.
http://msdn.microsoft.com/en-us/library/microsoft.identitymodel.protocols.wstrust.requestsecuritytokenresponse.requesteddisplaytoken.aspx
Assuming your security token service supported it, the display token could contain a claim set that would allow you to flow your permissions into the UI, say to disable controls that are bound to services the user cannot call. The display token is an extension to WS-Trust that was implemented for CardSpace so it it not likely to be very widely supported outside of the Windows world.
Be aware though, that some people think the display token is bad news and violates the 1st law of identity:
http://www.francisshanahan.com
While other people think it is a reasonable and pragmatic solution to a common problem:
http://blogs.msdn.com/b/vbertocci/archive/2007/10/31/on-displaytoken.aspx
There are two general type to implement checking logic:
Share library. Example is "RIA Services + Silverlight".
Pluses: simple to implement.
Minuses: no interoperability (only .NET); required client update for every library changing.
Implement common method validation in service part.
Pluses: interoperability, no need for client update if checking logic changed
Minuses: may be to complex because it is only on you
If we use SOA it is better to use second choice, if only you are not using applications only in your company where .NET is everywhere.
Example
Let us consider common example. We have a windows/wpf form. And there are two fields: "surname" of type string, "age" of type int; and a button "Save". We need to implement some check on client side
1) for some users button "Save" is disabled;
2) surname cannot be empty and max length is 256;
3) age cannot be less than 0;
Invoking method to save is
void Save(string surname, int age);
Create second method in the service, which return object type of PermissonAnswerDTO with validation information;
PermissonAnswerDTO SaveValidate(string surname, int age);
and main validation method
// If arguments are wrong
[FaultContract(typeof(NotSupportedException))]
// If the user have permisson to invoke this method
[FaultContract(typeof(CustomNotEnoughPermission))]
PermissonAnswerDTO Validate(string methodName, object[] methodParams);
Validation.
Invoke Validate("SaveValidate", null) on window loading. If exception of type CustomNotEnoughPermission is throwed then we block "Save" button.
If user can save then invoke user's data Validate("SaveValidate", object[2]{"Surname", "-60"};. -60 is not valid so we get answer object of type PermissonAnswerDTO with information:
ParameterName: "age",
ExceptionMessage: "age cannot be less then null".
And we can gracefully show this information to user.
My thought on this is that some day Microsoft will implement this and call as new technology as it always does. Mostly Microsoft's technologies really are not so revolutionary as it is advertised. Examples are Windows Identity Foundation and Reactive Extensions.
Full example
[DataContract]
public class ParameterExceptionExplanaitonDTO
{
[DataMember]
public string ParameterName;
[DataMember]
public string ExceptionMessage;
}
[DataContract]
public class PermissonAnswerDTO
{
[DataMember]
public bool IsValid;
[DataMember]
public ParameterExceptionExplanaitonDTO[] ParameterExceptions;
}
public class Service1 : WcfContracts.IService1
{
// If arguments are wrong
[FaultContract(typeof(NotSupportedException))]
// If the user have permisson to invoke this method
[FaultContract(typeof(CustomNotEnoughPermission))]
public PermissonAnswerDTO Validate(string methodName, object[] methodParams)
{
//1) Using Reflection find the method with name = <methodName + Validate>
//2) Using Reflection cast each object in "object[] methodParams" to the required type
//3) Invoke method
}
private PermissonAnswerDTO GetUserNameValidate(int id)
{
//logic to check param
}
public string GetUserName(int id)
{
// if the user calls method we need validate parameter
GetUserNameValidate(id);
//some logic to retreive name
}
}
Adding a service reference to a web service (this is all WCF) in Visual Studio produces some generated code including a client-side restatement of the interface being exposed.
I understand why this interface is generated: you might be consuming a 3rd party service and not have access to the actual interface.
But I do, and the two are not assignment compatible even though the transparent proxy does indeed exactly implement the interface to which I want to cast.
I can use reflection, but that's ugly. Is there some way to defeat this faux type safety and inject metadata to so I can use an interface with a class?
My specific problem departs from the norm in complicated ways that have to do with a single client that uses some derivatives of a base class directly and uses others remotely via service references. The base class for each server needs to keep references to subscribing clients in a collection for enumeration to notify events, and the problem was type varied due to the use of proxies.
None of these answers solves my specific problem, yet every single answer was instructive and helpful. I found my own solution (use a dual binding) but I would never have figured it out if you hadn't radically improved my understanding of the whole business.
Three excellent answers. How to choose just one? I choose the first, because it directly solves the problem I first thought I had.
If you already have the contract dll at the client, you don't even need a service reference (unless you are using it to write the setup code for you) - you can simply subclass ClientBase and expose the Channel, and use that directly - something like (no IDE handy...):
public class WcfClient<T> : ClientBase<T> where T : class
{
public new T Channel {get {return base.Channel;}}
}
Then you can just do things like:
using(var client = new WcfClient<IFoo>())
{
client.Channel.Bar(); // defined by IFoo
}
You still need the configuration settings in the config to determine the address, binding, etc - but less messy than proxy generation. Also, you might choose to re-implement IDipsoable to deal with the fact that WCF proxies can throw in Dispose() (which is bad):
public class WcfClient<T> : ClientBase<T>, IDisposable where T : class
{
public new T Channel {get {return base.Channel;}}
void IDisposable.Dispose() {
try {
switch(State) {
case CommunicationState.Open: Close(); break;
// etc
}
} catch {} // swallow it down (perhaps log it first)
}
}
When you add the service reference, go to "Advanced" and make sure "Reuse types in referenced assemblies" is selected and that the assembly containing your interface definition is selected. You can also do this with an existing service reference by right clicking on it and going to "Configure".
In order to return an interface from a service you need to use the KnownType attribute:
http://weblogs.asp.net/avnerk/archive/2006/07/31/WCF-Serialization-part-1_3A00_-Interfaces_2C00_-Base-classes-and-the-NetDataContractFormatSerializer.aspx
If you want to return a custom type from the service:
http://msdn.microsoft.com/en-us/library/bb628653.aspx
Does any of that help?