2017-02-21 33 views
2

我在一個基於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值(在控制器中可用)到具體類型的構造函數,在運行時它是否可用?

+0

將httpcontext包裝在抽象中。 – Nkosi

+0

你有沒有考慮從這裏獲取uri System.Web.HttpContext.Current.Request.Url,在StructuredUrlTester的構造函數裏面 – Dimitri

+0

你有明確的理由爲什麼你需要實現這個邏輯背後的抽象?顯然,我只是把它放到幫助程序/擴展方法中... – kayess

回答

2

包裹在一個抽象所需的功能:

public interface IUriProvider { 
    Uri Current { get; } 
} 

重構測試儀類:

public class StructuredUrlTester : IStructuredUrlTester { 
    // Expose public getters for parts of the uri.Host value 
    bool MyBooleanProperty { get; private set; } 

    public StructuredUrlTester(IUriProvider provider) { 
     Uri uri = provider.Current; 
     // Test the value of uri.Host and extract parts via regex 
    } 
} 

的提供者實現換行的Request.Url

public class UriProvider : IUriProvider { 
    public Uri Current { get { return HttpContext.Current.Request.Url; } } 
} 

,並注意Current財產實際上應該被稱爲機智hin一個控制器的動作,其中HttpContext及其請求可用。

+0

絕對好,只是按我的需要工作。我現在可以看到,如何使用提供程序意味着在構造「MyController」之前不會訪問'HttpContext'(通過Ninject意味着'StructuredUrlTester'也正在構建中),此時已填充Request對象並且可用。感謝您的幫助! –