Parameterized Factories Using Ninject

后端 未结 1 1933
臣服心动
臣服心动 2021-02-11 08:59

How to make Ninject to instantiate object based on variable on run time?.

I am trying to inject the correct Repository in The Controller action - MVC 3 - based on

1条回答
  •  佛祖请我去吃肉
    2021-02-11 09:30

    You could inject an Abstract Factory (probably just a Func) and then have it all implemented via adding the following to your RegisterServices:

    Bind().To().Named("KIA")
    Bind().To().Named("BMW")
    Bind>()
        .ToMethod( ctx=> name => ctx.Get( name));
    

    In your ctor:

    class MyController
    {
        readonly Func _createRepository;
    
        public MyController(Func createRepository)
        {
            _createRepository = createRepository;
        }
    

    Then, in your action:

    [HttpPost]
    public ActionResult SearchResult(FormCollection values)
    {
        string carModel  = values["model"];
    
         using( ICarRepository myRepository = _createRepository( carModel)) 
         {
                ... 
         } 
    }
    

    0 讨论(0)
提交回复
热议问题