我的項目使用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()
{ }
}
本文檔應該把你放在正確的路徑:https://github.com/ninject/Ninject/wiki/Contextual-Binding –
檢查此https://github.com/ninject/Ninject/wiki/Multi-injection –