2012-03-19 63 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" } 
);