2016-09-16 60 views
2

我的項目使用ASP.NET MVC和Ninject將抽象接口綁定到具體實現,所以我的網站Controllers可以獲取數據。但是,現在我想添加從不同位置獲取相同數據集的選項。這將需要我使用的抽象接口的不同實現,但所有方法調用都是相同的。我仍然想繼續使用Ninject,但我不想僅僅複製已有的界面,並將其命名爲不同的界面。如何在一個接口的多個實現中使用Ninject和MVC?

編輯1:我剛纔意識到我從未正式提出過一個問題。如何告知Ninject和/或ASP.NET控制器工廠僅基於查詢字符串使用抽象類的一個實現而不是另一個實現?

這裏就是我談論的例子:

// Global.asax.cs 

public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 
     // Using Ninject resolver 
     NinjectResolver.SetResolver(new NinjectResolver()); 
    } 
} 

// NinjectResolver.cs 

public class NinjectResolver : IDependencyResolver 
{ 
    private IKernel kernel; 

    public NinjectResolver() 
    { 
     kernel = new StandardKernel(); 
     AddBindings(); 
    } 

    public void AddBindings() 
    { 
     // I don't know what to do here: 

     //kernel.Bind<IFooModel>().To<FooModelImplementation>(); 
     //kernel.Bind<IFooModel>().To<FooModelImplementation2>(); 
    } 
} 

的接口實現:

// FooModel.cs 

public interface IFooModel 
{ 
    FooData GetData(int dataID); 
} 

public class FooData 
{ 
    public string Field1 {get; set;} 
    public string Field2 {get; set;} 
    public string Field3 {get; set;} 
    // ... 
    public FooData() 
    { } 
} 

public class FooModelImplementation : IFooModel 
{ 
    public FooModelImplementation() 
    { } 

    public FooData GetData(int dataID) 
    { 
     // Get data... 
    } 
} 

public class FooModelImplementation2 : IFooModel 
{ 
    public FooModelImplementation2() 
    { } 

    public FooData GetData(int dataID) 
    { 
     // Get data from source 2... 
    } 
} 

而且我Controller

// FooController.cs 

public FooController : BaseController 
{ 
    private IFooModel mFooModel; 

    public FooController(IFooModel fooModel) 
    { 
     mFooModel = fooModel; 
    } 

    // http://www.example.com/Foo?dataID=1&location=2 
    public ViewResult FooView(int dataID) 
    { 
     // Here I want the mFooModel to be an instance of FooModelImplementation2 
     // because "location" is 2. How do I do this? 
     FooData data = mFooModel.GetData(dataID); 
     FooViewModel viewModel = new FooViewModel 
     { 
      Field1 = data.Field1; 
      Field2 = data.Field2; 
     }; 
     return View(viewModel); 
    } 
} 

public class FooViewModel 
{ 
    public string Field1 {get; set;} 
    public string Field2 {get; set;} 

    public FooViewModel() 
    { } 
} 
+2

本文檔應該把你放在正確的路徑:https://github.com/ninject/Ninject/wiki/Contextual-Binding –

+0

檢查此https://github.com/ninject/Ninject/wiki/Multi-injection –

回答

1

使用工廠擴展(https://github.com/ninject/Ninject.Extensions.Factory/wiki/Factory-interface%3A-Referencing-Named-Bindings )將工廠注入控制器而不是模型。

該工廠可用於獲取命名實例。創建兩個命名綁定並在控制器中選擇適當的綁定。

+0

Hi @Remo。請問你認爲你可以看看這個問題嗎? http://stackoverflow.com/questions/40198294/how-to-configure-ninject-so-that-it-creates-a-single-instance-per-controller?noredirect=1#comment67673663_40198294 – eddy

相關問題