Dirk
Dirk

Reputation: 934

Ninject binding based on the typeof a contract

I'm not really sure how to solve this problem, or even really what to search for. Here is what I am trying to do.

Given a base class, that is a contract

public class BaseContract
{ }

Which has two sublcasses

public class Contract1 : BaseContract
{
    public string Name { get; set; }
    public string Surname { get; set; }

}

public class Contract2 : BaseContract
{
    public int Id { get; set; }
    public string Stuff { get; set; }
}

I would like to bind an interface IMyClass to either MyClass1 or MyClass2 depending on which contract I receive. So the invoking method will be something like.

public void Test(BaseContract contract)
{
   var classToGet = kernel.Get<IMyClass>(typeof(contract));
}

I have tried binding it as follows

        Bind<IMyClass>()
            .To<MyClasses2>()
            .WithMetadata("ContractType", typeof(Contract2));

but that didn't seem to help.

How can I achieve this type of binding with Ninject ?

Upvotes: 0

Views: 131

Answers (1)

cvbarros
cvbarros

Reputation: 1694

You can achieve this using Ninject Named Bindings, as follows:

Bind<IMyClass>().To<MyClasses1>().Named(typeof(Contract1).Name);
Bind<IMyClass>().To<MyClasses2>().Named(typeof(Contract2).Name);

Then, you can perform the injection using one of the common injection patterns (Constructor, Property, Method, etc, by doing so:

public class ClassWithDependency
{
    // To achieve property injection
    [Inject, Named("Contract2")]
    public IMyClass Contract2Instance {get; set;}


    // Constructor injection
    public ClassWithDependency([Named("Contract2") contract2Instance)
    {
         //Save reference to your dependency here
    }
}

Or you can even use the Service Locator (like your example, but not recommended) to achieve what you want:

public void Test(BaseContract contract)
{
   var classToGet = kernel.Get<IMyClass>(typeof(contract).Name);
}

Hope that helps!

Upvotes: 1

Related Questions