简体   繁体   中英

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 eg

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.

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 (eg <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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM