Question

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

Was it helpful?

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top