How does a WCF proxy implement ICommunicationObject if it's methods aren't visible? - wcf

How does a WCF channel (created via ChannelFactory) implement ICommunicationObject, but doesn't expose the Close() method, for example, unless you cast the proxy to ICommunicationObject? Does that make sense?
I got to thinking about that on the way home today and couldn't figure it out in my head. Maybe I'm asking the wrong question? Maybe I'm asking a stupid question? :)
Is it some kind of ninja trick?

This is done via Explicit Interface Implementation.
Suppose you have an interface, like so:
public interface IFoo
{
void Foo();
}
You can implement this normally:
public class Bar : IFoo
{
public void Foo() {} // Implicit interface implementation
}
Alternatively, you can implement the interface members explicitly, which requires the cast:
public class Baz : IFoo
{
void IFoo.Foo() {} // This will require casting the object to IFoo to call
}
This can be very useful at times. For example, it is often done to implement IDisposable in classes where the preferred API would be to call .Close(), for example. By implementing IDisposable explicitly, you "hide" the Dispose() method, but still allow the class instance to be used via a using statement.

The Channel class implements the ICommunicationObject interface explicitly. Here's an example demonstrating the difference between explicit interface implementation and implicit interface implementation:
internal interface IExample
{
void DoSomething();
}
class ImplicitExample : IExample
{
public void DoSomething()
{
// ...
}
}
class ExplicitExample : IExample
{
void IExample.DoSomething()
{
// ...
}
}
class Consumer
{
void Demo()
{
var explicitExample = new ExplicitExample();
// explicitExample.DoSomething(); <-- won't compile
((IExample)explicitExample).DoSomething(); // <-- compiles
var implicitExample = new ImplicitExample();
implicitExample.DoSomething(); // <-- compiles
}
}
Here is a link to the an MSDN article on this subject: http://msdn.microsoft.com/en-us/library/ms173157.aspx

Related

Class implementing Interface with subtype arguments

Why I cannot do that? I get compilation error.
public interface A {
void update(Object a);
}
public class B implements A{
void update(Long a) {
}
}
That is Java 8
I do not see here violating any OO principle.
That's really make my time difficult to implement a generic API...
(I try to get Generics out of the play because the generic API gets counter-intuitive)
You get a compilation error because void update(Long a) does not implement void update(Object a).
You can implement it as follows:
public class B implements A {
void update(Object o) {
if (!(o instanceof Long)) {
// possibly throw an exception
}
Long a = (Long) o;
...
}
}
A class that implements an interface must implement all the methods declared in the interface. The methods must have the exact same signature (name + parameters) as declared in the interface. The class does not need to implement (declare) the variables of an interface. Only the methods.
Source:
http://tutorials.jenkov.com/java/interfaces.html#:~:text=A%20class%20that%20implements%20an,Only%20the%20methods.

ninject binding for specify class

if I have the interface interfaceA
public interface IInterfaceA
{
void MethodA();
void MethodB();
}
and I have the classA
class ClassA:IInterfaceA
{
public void MethodA()
{
}
public void MethodB()
{
}
}
it's ok that I use ninject's bind,but when it comes that I have a method that called MethodC,I think the method should only exists in classA(just for classA) and should not be defined in InterfaceA,so how to use ninject'bind when just calling like this:
var a = _kernel.get<IInterfaceA>()
should I convert the result into ClassA ? (is that a bad habbit?) or there are another solution
Usually this is needed when you want interface separation but need both interfaces to be implemented by the same object since it holds data relevant to both interfaces. If that is not the case you would be able to separate interfaces and implementation completely - and then you should do so.
For simplicitys sake i'm going to asume Singleton Scope, but you could also use any other scope.
Create two interfaces instead:
public interface IInterfaceA {
{
void MethodA();
}
public interface IInterfaceC {
void MethodC();
}
public class SomeClass : IInterfaceA, IInterfaceC {
....
}
IBindingRoot.Bind<IInterfaceA, IInterfaceB>().To<SomeClass>()
.InSingletonScope();
var instanceOfA = IResolutionRoot.Get<IInterfaceA>();
var instanceOfB = IResolutionRoot.Get<IInterfaceB>();
instanceOfA.Should().Be(instanceOfB);
Does this answer your question?

design pattern query

i have a question regarding design patterns.
suppose i want to design pig killing factory
so the ways will be
1) catch pig
2)clean pig
3) kill pig
now since these pigs are supplied to me by a truck driver
now if want to design an application how should i proceed
what i have done is
public class killer{
private Pig pig ;
public void catchPig(){ //do something };
public void cleanPig(){ };
public void killPig(){};
}
now iam thing since i know that the steps will be called in catchPig--->cleanPig---->KillPig manner so i should have an abstract class containing these methods and an execute method calling all these 3 methods.
but i can not have instance of abstract class so i am confused how to implement this.
remenber i have to execute this process for all the pigs that comes in truck.
so my question is what design should i select and which design pattern is best to solve such problems .
I would suggest a different approach than what was suggested here before.
I would do something like this:
public abstract class Killer {
protected Pig pig;
protected abstract void catchPig();
protected abstract void cleanPig();
protected abstract void killPig();
public void executeKillPig {
catchPig();
cleanPig();
killPig();
}
}
Each kill will extend Killer class and will have to implement the abstract methods. The executeKillPig() is the same for every sub-class and will always be performed in the order you wanted catch->clean->kill. The abstract methods are protected because they're the inner implementation of the public executeKillPig.
This extends Avi's answer and addresses the comments.
The points of the code:
abstract base class to emphasize IS A relationships
Template pattern to ensure the steps are in the right order
Strategy Pattern - an abstract class is as much a interface (little "i") as much as a Interface (capital "I") is.
Extend the base and not use an interface.
No coupling of concrete classes. Coupling is not an issue of abstract vs interface but rather good design.
public abstract Animal {
public abstract bool Escape(){}
public abstract string SaySomething(){}
}
public Wabbit : Animal {
public override bool Escape() {//wabbit hopping frantically }
public override string SaySomething() { return #"What's Up Doc?"; }
}
public abstract class Killer {
protected Animal food;
protected abstract void Catch(){}
protected abstract void Kill(){}
protected abstract void Clean(){}
protected abstract string Lure(){}
// this method defines the process: the methods and the order of
// those calls. Exactly how to do each individual step is left up to sub classes.
// Even if you define a "PigKiller" interface we need this method
// ** in the base class ** to make sure all Killer's do it right.
// This method is the template (pattern) for subclasses.
protected void FeedTheFamily(Animal somethingTasty) {
food = somethingTasty;
Catch();
Kill();
Clean();
}
}
public class WabbitHunter : Killer {
protected override Catch() { //wabbit catching technique }
protected override Kill() { //wabbit killing technique }
protected override Clean() { //wabbit cleaning technique }
protected override Lure() { return "Come here you wascuhwy wabbit!"; }
}
// client code ********************
public class AHuntingWeWillGo {
Killer hunter;
Animal prey;
public AHuntingWeWillGo (Killer aHunter, Animal aAnimal) {
hunter = aHunter;
prey = aAnimal;
}
public void Hunt() {
if ( !prey.Escape() ) hunter.FeedTheFamily(prey)
}
}
public static void main () {
// look, ma! no coupling. Because we pass in our objects vice
// new them up inside the using classes
Killer ElmerFudd = new WabbitHunter();
Animal BugsBunny = new Wabbit();
AHuntingWeWillGo safari = new AHuntingWeWillGo( ElmerFudd, BugsBunny );
safari.Hunt();
}
The problem you are facing refer to part of OOP called polymorphism
Instead of abstract class i will be using a interface, the difference between interface an abstract class is that interface have only method descriptors, a abstract class can have also method with implementation.
public interface InterfaceOfPigKiller {
void catchPig();
void cleanPig();
void killPig();
}
In the abstract class we implement two of three available methods, because we assume that those operation are common for every future type that will inherit form our class.
public abstract class AbstractPigKiller implements InterfaceOfPigKiller{
private Ping pig;
public void catchPig() {
//the logic of catching pigs.
}
public void cleanPig() {
// the logic of pig cleaning.
}
}
Now we will create two new classes:
AnimalKiller - The person responsible for pig death.
AnimalSaver - The person responsible for pig release.
public class AnimalKiller extends AbstractPigKiller {
public void killPig() {
// The killing operation
}
}
public class AnimalSaver extends AbstractPigKiller {
public void killPing() {
// The operation that will make pig free
}
}
As we have our structure lets see how it will work.
First the method that will execute the sequence:
public void doTheRequiredOperation(InterfaceOfPigKiller killer) {
killer.catchPig();
killer.cleanPig();
killer.killPig();
}
As we see in the parameter we do not use class AnimalKiller or AnimalSever. Instead of that we have the interface. Thank to this operation we can operate on any class that implement used interface.
Example 1:
public void test() {
AnimalKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `AnimalKilleraKiller `
AnimalSaver aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
Example 2:
public void test() {
InterfaceOfPigKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `InterfaceOfPigKiller `
InterfaceOfPigKiller aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
The code example 1 and 2 are equally in scope of method doTheRequiredOperation. The difference is that in we assign once type to type and in the second we assign type to interface.
Conclusion
We can not create new object of abstract class or interface but we can assign object to interface or class type.

C# OO Design: case when only ONE abstract method is needed

I have 2 classes that have the exact same logic/workflow, except in one method.
So, I created a abstract base class where the method that differs is declared as abstract.
Below is some sample code to demonstrate my design; can anyone offer suggestions on a better approach or am I heading in the right direction.
I didn't use an interface because both derived classes B and C literally share most of the logic. Is there a better way to do what I am doing below via dependency injection?
public abstract class A
{
public void StageData()
{
// some logic
DoSomething();
}
public void TransformData();
public abstract DoSomething();
}
public class B : A
{
public override void DoSomething()
{
// Do Something!
}
}
public class C : A
{
public override void DoSomething()
{
// Do Something!
}
}
There is nothing wrong with what you have done. To introduce dependency injection into this design would be messy and overkill - you would have to pass in a delegate:
public class ABC
{
public ABC(Action z)
{
_doSomethingAction = z;
}
public void DoSomething()
{
_doSomthingAction.Invoke();
}
private Action _doSomthingAction;
}
There would be few reasons why you want to use this approach - one would be if you needed to execute a callback. So stick with the pattern you have, don't try to overcomplicate things.

Prevent Ninject from calling Initialize multiple times when binding to several interfaces

We have a concrete singleton service which implements Ninject.IInitializable and 2 interfaces. Problem is that services Initialize-methdod is called 2 times, when only one is desired. We are using .NET 3.5 and Ninject 2.0.0.0.
Is there a pattern in Ninject prevent this from happening. Neither of the interfaces implement Ninject.IInitializable. the service class is:
public class ConcreteService : IService1, IService2, Ninject.IInitializable
{
public void Initialize()
{
// This is called twice!
}
}
And module looks like this:
public class ServiceModule : NinjectModule
{
public override void Load()
{
this.Singleton<Iservice1, Iservice2, ConcreteService>();
}
}
where Singleton is an extension method defined like this:
public static void Singleton<K, T>(this NinjectModule module) where T : K
{
module.Bind<K>().To<T>().InSingletonScope();
}
public static void Singleton<K, L, T>(this NinjectModule module)
where T : K, L
{
Singleton<K, T>(module);
module.Bind<L>().ToMethod(n => n.Kernel.Get<T>());
}
Of course we could add bool initialized-member to ConcreteService and initialize only when it is false, but it seems quite a bit of a hack. And it would require repeating the same logic in every service that implements two or more interfaces.
Thanks for all the answers! I learned something from all of them! (I am having a hard time to decide which one mark correct).
We ended up creating IActivable interface and extending ninject kernel (it also removed nicely code level dependencies to ninject, allthough attributes still remain).
Ninject 3
Ninject 3.0 now supports multiple generic types in the call to bind, what you are trying to do can be easily accomplished in a single chained statement.
kernel.Bind<IService1, IService2>()
.To<ConcreteService>()
.InSingletonScope();
Ninject 2
You are setting up two different bindings K=>T and L=>T. Requesting instances of L will return transient instances of T. Requesting K will return a singleton instance of T.
In Ninject 2.0, an objects scope is per service interface bound to a scope callback.
When you have
Bind<IFoo>...InSingletonScope();
Bind<IBar>...InSingletonScope();
you are creating two different scopes.
You are saying
"Binding to IFoo will resolve to the same object that was returned
when .Get was called."
and
"Binding to IBar will resolve to the same object that was returned
when .Get was called."
you can chain the bindings together, but you will need to remove IInitializable as it will cause duplicate initialization when the instance is activated:
kernel.Bind<IBoo>()
.To<Foo>()
.InSingletonScope();
.OnActivation(instance=>instance.Initialize());
kernel.Bind<IBaz>()
.ToMethod( ctx => (IBaz) ctx.Kernel.Get<IBoo>() );
or
kernel.Bind<Foo>().ToSelf().InSingletonScope()
.OnActivation(instance=>instance.Initialize());
kernel.Bind<IBaz>().ToMethod( ctx => ctx.Kernel.Get<Foo>() );
kernel.Bind<IBoo>().ToMethod( ctx => ctx.Kernel.Get<Foo>() );
in order to get multiple interfaces to resolve to the same singleton instance. When I see situations like this, I always have to ask, is your object doing too much if you have a singleton with two responsibilities?
Update : Pretty sure using V3's multiple Bind overloads will address this; See this Q/A
Good question.
From looking at the source, the initialize bit happens after each Activate. Your Bind...ToMethod counts as one too. The strategy is pretty uniformly applied - there's no way to opt out in particular cases.
Your workaround options are to use an explicit OnActivation in your Bind which will do it conditionally (but to do that in a general way would require maintaining a Set of initialized objects (havent looked to see if there is a mechanism to stash a flag against an activated object)), or to make your Initialize idempotent through whatever means is cleanest for you.
EDIT:
internal interface IService1
{
}
internal interface IService2
{
}
public class ConcreteService : IService1, IService2, Ninject.IInitializable
{
public int CallCount { get; private set; }
public void Initialize()
{
++CallCount;
}
}
public class ServiceModule : NinjectModule
{
public override void Load()
{
this.Singleton<IService1, IService2, ConcreteService>();
}
}
Given the following helpers:
static class Helpers
{
public static void Singleton<K, T>( this NinjectModule module ) where T : K
{
module.Bind<K>().To<T>().InSingletonScope();
}
public static void Singleton<K, L, T>( this NinjectModule module )
where T : K, L
{
Singleton<T, T>( module );
module.Bind<K>().ToMethod( n => n.Kernel.Get<T>() );
module.Bind<L>().ToMethod( n => n.Kernel.Get<T>() );
}
}
#Ian Davis et al. The problem is that:
class Problem
{
[Fact]
static void x()
{
var kernel = new StandardKernel( new ServiceModule() );
var v1 = kernel.Get<IService1>();
var v2 = kernel.Get<IService2>();
var service = kernel.Get<ConcreteService>();
Console.WriteLine( service.CallCount ); // 3
Assert.AreEqual( 1, service.CallCount ); // FAILS
}
}
Because each activation (per Bind) initialises each time.
EDIT 2: Same when you use the following slightly more stripped down version:
static class Helpers
{
public static void Singleton<K, L, T>( this NinjectModule module )
where T : K, L
{
module.Bind<T>().ToSelf().InSingletonScope();
module.Bind<K>().ToMethod( n => n.Kernel.Get<T>() );
module.Bind<L>().ToMethod( n => n.Kernel.Get<T>() );
}
}
I think one of the option is, you create the object your self in the module and bind your object the each of the interfaces.
BTW, try not to use any container specific code in your production code. If you have to do that, use some helper and isolate them in the module project.
public class ServiceModule : NinjectModule
{
public override void Load()
{
ConcreteService svc = new ConcreteService();
Bind<IService1>().ToConstant(svc);
Bind<IService2>().ToConstant(svc);
....
}
}