2012-03-19 59 views
0

我想建立一個檢查數據庫的約束。我正在使用Ninject,但由於某種原因,它在啓動時並未創建我的存儲庫的新實例。Routeconstraint與Ninject和dbcontext

的global.asax.cs

// Content 
routes.MapRoute(
     "Content Language Route", 
     "{languageID}/List", 
      new { controller = "Content", action = "Index", 
      new { languageID = new LanguageRouteConstraint() }, 
      new string[] { "MyProj.MVC.Controllers" } 
     ); 
..... 
kernel.Bind<IContentRepository>().To<ContentRepository>(); 

約束

public class LanguageRouteConstraint : IRouteConstraint 
{ 
#region IRouteConstraint Members 

private readonly IContentRepository _contentRepository; 

public LanguageRouteConstraint(IContentRepository contentRepository) 
{ 
    this._contentRepository = contentRepository; 
} 

public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
{ 
if (routeDirection == RouteDirection.IncomingRequest) 
{ 
    string languageID = values["languageID"].ToString(); 

    if (String.IsNullOrEmpty(languageID)) 
    return false; 

    MyProj.MVC.Models.Language language = _contentRepository.GetLanguage(languageID); 

    return (language != null); 
    } 
    return false; 
    }  
#endregion 
} 

使用Ninject存儲庫工作在控制器,但我需要修改gobal ASA的路線爲它使它工作?

回答

0

解決這樣的:

// Content 
routes.MapRoute("Content Language Route", 
     "{languageID}/List", 
     new { controller = "Content", action = "Index", 
     new 
     { 
     languageID = new LanguageRouteConstraint(
      DependencyResolver.Current.GetService<IContentRepository>()) 
     }, 
    new string[] { "MyProj.MVC.Controllers" } 
);