JNN
JNN

Reputation: 38

Ninject Dependency Injection Using Reflection

public DefaultRepositoryRegistry(IKernel kernel)
{
    foreach (var tuple in DefaultContractList())
    {
        var iRepo = tuple.Item1;
        var repo = tuple.Item2;
    }
}

private static IEnumerable<Tuple<Type, Type>> DefaultContractList()
{
    var contractList = new List<Tuple<Type, Type>>()
    {
        #region Mongo

        Tuple.Create(typeof (IMongoRepository), typeof (MongoRepository)),

        #endregion Mongo
    };

    return contractList;
}

I am unable to do dynamic binding e.g.

foreach (var tuple in DefaultContractList())
{
    var iRepo = tuple.Item1;
    var repo = tuple.Item2;

    kernel.Bind<iRepo>().To<repo>();
}

Any help as to why Ninject doesn't accept this type of binding? I am doing this so that one can use the same set of services in for different dependency injection frameworks.

Upvotes: 2

Views: 874

Answers (1)

FMM
FMM

Reputation: 4329

This syntax probably won't compile:

foreach (var tuple in DefaultContractList())
{
    var iRepo = tuple.Item1;
    var repo = tuple.Item2;

    kernel.Bind<iRepo>().To<repo>();
}

The bits inside the angle brackets are called type parameters (e.g. <iRepo> and <repo>), and they should be the actual type names, not variables of type System.Type. It just so happens, though, that Ninject has an alternate form of binding that will probably work perfectly for you:

foreach (var tuple in DefaultContractList())
{
    var iRepo = tuple.Item1;
    var repo = tuple.Item2;

    kernel.Bind(iRepo).To(repo);
}

Upvotes: 2

Related Questions