我在一個基於MVC5的網站中使用Ninject 3,並試圖找出如何讓DI使用一種類型來測試傳入的Uri.Host
值的屬性它的構造函數。我希望綁定以某種方式提供當前的URL。最小的結構,我最初嘗試是:Ninject綁定的類型需要當前Request.Url
public class StructuredUrlTester : IStructuredUrlTester
{
// Expose public getters for parts of the uri.Host value
bool MyBooleanProperty { get; private set; }
public StructuredUrlTester(Uri uri)
{
// Test the value of uri.Host and extract parts via regex
}
}
// In Global.asax.cs
public class MvcApplication : NinjectHttpApplication
{
protected override IKernel CreateKernel()
{
kernel.Bind<IStructuredUrlTester>()
.To<StructuredUrlTester>()
.InTransientScope();
.WithConstructorArgument("uri", Request.Url);
}
}
// In MyController.cs
public class MyController : Controller
{
private readonly IStructuredUrlTester _tester;
public ContentPageController(IStructuredUrlTester tester)
{
this._tester = tester;
}
public ActionResult Index()
{
string viewName = "DefaultView";
if (this._tester.MyBooleanProperty)
{
viewName = "CustomView";
}
return View(viewName);
}
}
由於CreateKernel()
通話發生在Request
對象可用前,.WithConstructorArgument()
部分拋出異常(「System.Web.HttpException:請求不可用在這方面「)。
如何提供界面與具體類型的綁定,同時還能夠提供例如HttpContext.Current.Request.Url
值(在控制器中可用)到具體類型的構造函數,在運行時它是否可用?
將httpcontext包裝在抽象中。 – Nkosi
你有沒有考慮從這裏獲取uri System.Web.HttpContext.Current.Request.Url,在StructuredUrlTester的構造函數裏面 – Dimitri
你有明確的理由爲什麼你需要實現這個邏輯背後的抽象?顯然,我只是把它放到幫助程序/擴展方法中... – kayess