I want to know is it possible to create one wcf proxy client that have separated classes that hold number of methods ?
Meaning for example :
SomeClient _client = new SomeClient();
_client.Class1.SomeMethod();
_client.Class2.SomeMethod();
all of that in the same service and interface ?
in all what i want is to group the method under one class with distinc name and in one service.
Thanks
Guy
You're not going to be able to do this with a ServiceReference WCF Proxy, no. It just doesn't generate the proxies that way.
You could wrap the proxy in classes that pass the methods you want to the proxy but otherwise do nothing.
Another option, if you have control over the service itself, is to separate the methods into separate services. Given your apparent desire to have separation of concerns, this may be a good option to pursue.
could you explain alittle bit more on the second part of your answer please. with example
There are multiple ways to accomplish this. This example is incomplete and doesn't feature important error handling and proxy instantiation. I'll leave that for you.
public class Svc1
{
private Proxy proxy;
public void Method1(string param)
{
Proxy.Method1(param);
}
}
public class Svc2
{
private Proxy proxy;
public int Method2()
{
return Proxy.Method2();
}
}
public class MegaProxy
{
public Svc1 Class1 {get; set;}
public Svc2 Class2 {get; set;}
}
i dont want the programmer of the client side use many services, you know just writing all of the using statement is confusing, i want to give it to him plan and simple under one proxy
Hmm... I see some unfortunate assumptions in your statement here. I'm guessing you're relatively new to WCF, and that's fine, but that means you haven't run into this problem yet: Never, ever use using on a WCF proxy. The reason is that the Dispose method of WCF proxies can throw in certain circumstances -- primarily f the service call faulted. This can lead to some surprisingly ugly problems if you're not aware of the issue. It's almost always best to use an Open Proxy => Call Service => Close Proxy paradigm instead.
That said, I don't think it would be too different for your client to call separate services than to call methods on separate fields of a single proxy. If anything, separate services would allow your client better control over when and how a proxy is created.
If you have control over the client code -- if you're providing the proxy itself as a .DLL, for example -- you could build a static class with static methods that instantiate the different proxies for the client.
Related
In the below adapter design pattern sample code, why a new class is introduced instead of using multiple interface in the client?
interface ITarget
{
List<string> GetProducts();
}
public class VendorAdaptee
{
public List<string> GetListOfProducts()
{
List<string> products = new List<string>();
products.Add("Gaming Consoles");
products.Add("Television");
products.Add("Books");
products.Add("Musical Instruments");
return products;
}
}
class VendorAdapter:ITarget
{
public List<string> GetProducts()
{
VendorAdaptee adaptee = new VendorAdaptee();
return adaptee.GetListOfProducts();
}
}
class ShoppingPortalClient
{
static void Main(string[] args)
{
ITarget adapter = new VendorAdapter();
foreach (string product in adapter.GetProducts())
{
Console.WriteLine(product);
}
Console.ReadLine();
}
}
I have the below queries related to the above code.
What, if ShoppingPortalClient directly inherits VendorAdaptee?
In which scenario we need adapter class?
why instead of simple inheritance a needed class, creating this pattern to access another class method?
Sometimes you have a given API that you can't change (legacy/external-library/etc...) and you want to make your classes be able to work with that API without changing their code.
Lets say you use an API which has an ISomethingToSerialize
public interface ISomethingToSerialize
{
object[] GetItemsToSerialize();
}
That API also has a Serialize function:
public class SerializationServices
{
byte[] Serialize(ISomethingToSerialize objectToSerialize);
}
Now you have a class in your code, and you don't want or not able to change it, let's call it MyUnchangeableClass.
This class doesn't implement ISomethingToSerialize but you want to serialize it using the API so you create AdapterClass which implement ISomethingToSerialize to allow MyUnchangeableClass to use it without implementing it by itself:
public class AdapterClass : ISomethingToSerialize
{
public AdapterClass(MyUnchangeableClass instance)
{
mInstance = instance;
}
MyUnchangeableClass mInstance;
public object[] GetItemsToSerialize()
{
return mInstance.SomeSpecificGetter();
}
}
Now you can use
MyUnchangeableClass instance = ... //Constructor or factory or something...
AdapterClass adapter = new AdapterClass(instance)
SerializationServices.Serialize(adapter);
to serialize an instance of MyUnchangeableClass even though it doesn't meet the requirements of the API by itself.
You've got the idea totally wrong. The VendorAdaptee is the instance of code that produce data, where the ShoppingPortalClient is the one who wants to consume it.
Let me explain what would be the real world situation. You are implementing the shop, and someone else has been implemented a service to give you data about their products(VendorAdaptee). The simple way of doing it is to simply call their methods and use the data, right? But it is their service and they might want to change it later while you don't want to upload your whole solution and release a new version. Therefore, you need an adapter in between to make sure that the data will be send to your real code with the format that you need, and you simply don't care about the address, method name or data format that has been supported by your vendor.
about your questions:
Inheritance is not in any way the case. Conceptually speaking, a shop is not a vendor in any way. considering the code, you have nothing similar in any of those 2, and the behavior is totally different. one is providing data while the other use it.
The main reason you would use an adapter is for legacy code that you don't want to mess with - or a third party that you won't to fit into a certain interface.
There are other reasons, usually depending on how you find easier to develop and if using the adapter design pattern makes sense to you. I don't see it as very useful in other cases though.
First of all I also don't think this is a good example for Adapter pattern. Adapter pattern is much meaningful when you can't directly use one particular kind of class(say A) in your class(say B), instead you implement another class(say C) which can be directly used inside your class (B) and it(C) can directly use the first one(A).
You might ask what will be the examples where B cannot directly use A. There's few.
A's methods don't return the type which is ideally needed by B.
So we don't to mess up with adding the conversion need by B inside B. Instead we give responsibility to C to do it for B.
It might not look natural for B to contain A. etc.
Back to your questions
(1) It is meaningful if you ask,
What, if ShoppingPortalClient directly 'uses' VendorAdaptee?
Just because it is the main class, it has been used as a demo, not to show the structure. And one thing to add, just because you want to call another class's method, don't inherit it unless it is meaningful. In this scenario composition is preferred. For the question why not 'using', just assume it cannot. But you rather ask why cannot. The answer I can give in this example is just assume it is not natural to call Adaptee. That's why I said it is not a good example. :)
(2), (3) I think you can get the answer from the description I have provided so far.
When using WCF, we can define a service contract:
[ServiceContract]
public interface IMyService
{
[OperationContract]
int MyOperation(int x);
}
Assume I open a servicehost at www.example.com/MyService, then one way to use this service from my client is
IMyService service =
new ChannelFactory<IMyService>(new BasicHttpBinding(),
new EndpointAddress("www.example.com/MyService")).CreateChannel();
int result = service.MyOperation(10);
So somehow, service implements IMyService, although that was never done explicitly. If I debug these lines, I can see that service is an instance of __TransparentProxy. As you can see from the source code, the comments in that class say
Transparent proxy magically creates a message that represents a call on it and delegates to the Real proxy to do the real remoting work.
To me this is indeed 'magic', but I guess there must be a logical explanation.
The pattern here can be very useful. What I would like is some class like Magic below (the syntax is incorrect, I know, otherwise I wouldn't need to ask). For the sake of argument, let's say I want this class to print the name of the method called.
public class Magic<T> : T {
// don't know what to do here
}
Such that I would be able to call
IMyService service = new Magic<IMyService>();
service.MyOperation(10);
And this would print:
MyOperation
Is something like this possible? (It should be, since __TransparentProxy does something similar.) And if so, how would this work?
There are a few articles on Codeplex that try to do something similar to what WCF does under the covers:
http://www.codeproject.com/Articles/43598/Emit-Proxy
http://www.codeproject.com/Articles/5511/Dynamic-Proxy-Creation-Using-C-Emit
The System.Reflection.Emit namespace is the underlying key, which can be used to dynamically create .NET assemblies and types in code.
Any one else running across this answer might want to look at Aspect Oriented Programming (AOP) in general
And possibly PostSharp specifically: https://www.postsharp.net/aop.net
I'm designing a WCF webservice that will potentially get called by 10,000+ plus separate clients at any given time. When the service gets called the service creates "Object1" class.
public List<string> AnswerClient() {
Object1 _hello = new Object1();
return _hello.AnswerClient();
}
Because the Object1 class needs to create other Object1 classes inside of it. It needs to create other subset Object1 classes. I was thinking of using static method in the Object1 class to create the other Object1 methods like
Object1.AnswerClient()
because I don't think I need to create a specific Object1() in the first place. If multiple clients call the service, will this Object1.AnswerClient() mess up the code because it is static? Because statics are specific to the class, all the clients seem to be affected?
How should I design this class. Client calls service, service creates object based on client data. That object inside of it creates like 20 more similar objects (splits the user data depending on the data).
Any help and insight would help. How should I design this generally speaking?
Thanks.
If the AnswerClient method doesn't, in and of itself, require any state other than state it creates, there should be no issue with making it static.
That being said, I would think about this differently. Is AnswerClient really something that is a function of Object1 (which also could get a better name)? Or is it a general purpose utility method? If it's logically tied to a specific "Object1" instance, then I'd leave it as an instance method. If it's more of a general utility, and has no directly relation to whatever "Object1" represents, make it static.
I would suggest you to look towards Factory design pattern to do what you described above.
So I have some code like this.
[DataContract]
public class Example
{
SomeClass _someVar;
[OnDeserializing]
public void OnDeserializing(StremingContext c)
{
_someVar = new SomeClass();
}
}
Here is the funny thing, OnDeserializing() gets called if I use the test debugging client from Visual Studio 2010. But if I try and host my WCF service and then call it from my own client it doesn't get called (or probably doesn't), because _someVar is always null.
Argh!
What else do I need to do?
Kind regards,
Fugu
WCF does not use standard .net serialization, so I'm not certain it will invoke your OnDeserializing method. However you can ask WCF to use an XmlSerializer, which should give you the behavior you want. Have a look at "Controlling the Serialization Process" here.
Further to PaulF's answer, your class is not a singleton - 2 calls to the service will by default instantiate Example twice and call the method once.
Because of this, there's really very little point in having any variables declared at a class level.
If you want to change this behaviour, have a look here for more information
I am using .NET 3.5 C#. I have a simple connection class with only two methods: OpenConnection() and CloseConnection(). I defined this class as Static so that I don't have to create an instance while calling methods. I want to know whether:
(1) I should create an interface with method definitions for OpenConnection and CloseConnection and thereby use this Interface with Connection class. There is no reason to use an interface but I was thinking whether the Connection can be made more professional.
(2) Is it fine to declare this class as Static?
There are two entirely different approaches
Singleton: Single object across the application.
In this case, you will have to take care of the locking mechanism as well.
class Connection
{
public static Connection Instance() {
if (_instance == null) {
lock (typeof(Connection)) {
if (_instance == null) {
_instance = new Connection();
}
}
}
return _instance;
}
protected Connection() {}
private static volatile Connection _instance = null;
}
Implement IDisposable:
Alternatively, you can implement IDisposable in your Connection class, and let it disposed automatically using the using keyword. For instance:
using(Connection c = new Connection(SomeConfiguration)) //Opens the connection.
{
Something(c);
}// Closes the connection. Dispose is implicitly called in the scope of the using statement.
Or if you want Generic Connection class, then Marc has responded with an excellent database connection class example here.
Regarding point 1; you can use interface; iff:
You want loose coupling, componentization, and maintainability in your code.
You want to provide guarantee that the classes shall behave exactly as methods/contracts defined in interface. For instance, in this case, if you extend your class from IDisposable, the interface imposes that not only objects can be disposed without getting compiler errors, but that they should be disposed. So, similar guarantees can be provided in your code by simply adhering to an interface.
You have a team that is going to working on a large module; and you want to keep code consistent; so you can define an interface and add some restrictions, that would help integrate the it easily. For instance:
You know you have a module that is going to handle alot of connections, different types of connections - some of which may be identified later during the development. But what you know for sure is that all types of connection shall be able to Open and Close; and you also want all of the developers to stick to this rule. So you can come up with an interface like:
interface IMyConnection
{
Open();//Opens the connection
Close();//Closes the connection
}
You expect have certain classes that does a lot of complex work and won't be finished before the rest of the project; then rest of the project can use the interface and avoid being dependent on that class.
You plan to deploy your product commercially; and want it to be extendable by 3rd party developers.
If you use interface, you cannot define Static method. (or in other word, static method is always pointing to the class defined, so the interface cannot provide abstraction at this point).
A class can be static, as long as you want everything shared, and extension to it is not necessary. But I would strongly recommend you to look at Singleton Pattern and Abstract Factory as alternative to your design problem.
interface IConnection {
void Connect();
void DisConnect();
}
class TCPCustomConnection : IConnection{
// implement other stuff
// Singleton Pattern
static IConnection Instance {
privateInstance = privateInstance ?? new TCPCustomConnection();
return privateInstance;
}
}
From what you said so far, I don't see how the interface adds value. If it does not add value, it should be eliminated from the design. The interface introduces two new problem: You need to get a pointer to the interface implementation, and usually you want to avoid asking for it repeatedly. So don't do it unless adds value (in a tangible, not metaphysical way) to your design.
An interface might add value if it simplifies unit testing of your code, or if it is important to remove the runtime dependency on the assembly that implements the connection. This is very fashionable these days.
simple a static class is requird, if it just used for demarcating operations like open and close connection, favor simplicity rather, dont code for future scenario until it is absolutely necessary and don't change existing working code till you reach a point where it is absolutely requirea
My advice:
(1) Why you need to write your own Connection class since it's "a simple connection"? None of the built-in classes meets your requirement?
(2) According to MS examples, it's really weird to make Open and Close methods static. We are used to this:
conn.Open();
conn.Close();
instead of:
MyConnection.Open(conn);
MyConnection.Close(conn);
(3) Using interfaces is a good idea, especially IDisposable:
class MyConnection : IDisposable
{
public void Dispose()
{
//close the connection and release resources
}
}
using (MyConnection conn = new MyConnection(connStr))
{
} //automatically Dispose()
If you have different connection type, like UDP, TCP, COM Port, ... using interface is good for manageability, but in the case which you have just one connection there is no need to use interface, also i think using static and singleton is not useful here, you should have a service for your tcp connection to always keep it up, and when you got disconnected you should be able to repair connection. for a good tcp server sample see http://fadd.codeplex.com/SourceControl/changeset/view/58859#1054893.
Even if you think that you'll only ever need one connection, I'd still use an instance class that implements an interface to handle it.
Why?
I can easily swap implementations if I need to (or refactor an existing one).
I can unit test things that depend on the class by mocking the connection.
I can more easily control the lifecycle of the connection (eg by using IDisposable).
Consumers of any API I write can see what my dependencies are.
If the single instance requirement does change, I don't have to unpick all the references to the static/singleton methods.
The testing point here is important: if you use a static reference to a fixed external resource, your code will be virtually impossible to unit test independently of that resource.
See this answer for a similar discussion about static versus instance classes and methods.