Inject different classes that implement the same interface using Ninject

前端 未结 2 846
Happy的楠姐
Happy的楠姐 2021-02-03 11:27

I am implementing the builder design pattern to construct different kinds of graph objects to be displayed on a WPF UI. I am using Ninject as my IOC container. However, I am try

2条回答
  •  Happy的楠姐
    2021-02-03 11:53

    I would suggest using Contextual bindings (named bindings specifically) to accomplish this. That way you can do something like:

    // called on app init
    kernel.Bind().To().Named("TempChartBuilder");   
    kernel.Bind().To("TempChartBuilder"));
    

    Where "TempChartBuilder" could be a variable that tells ninject which binding to resolve. So rather binding on the fly you would resolve on the fly but all binding could be defined up front. Typically IOC containers are stored at the application domain level and only need to be defined once. There may be specific cases where you need to bind dynamically but those should be rare.

    More info on contextual bindings: https://github.com/ninject/ninject/wiki/Contextual-Binding

提交回复
热议问题