加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC自定义路由约束和依赖注入

发布时间:2020-12-16 07:16:23 所属栏目:asp.Net 来源:网络整理
导读:在我的ASP.NET MVC 3应用程序中,我有一个如下定义的路由约束: public class CountryRouteConstraint : IRouteConstraint { private readonly ICountryRepositoryCountry _countryRepo; public CountryRouteConstraint(ICountryRepositoryCountry countryRep
在我的ASP.NET MVC 3应用程序中,我有一个如下定义的路由约束:

public class CountryRouteConstraint : IRouteConstraint {

    private readonly ICountryRepository<Country> _countryRepo;

    public CountryRouteConstraint(ICountryRepository<Country> countryRepo) {
        _countryRepo = countryRepo;
    }

    public bool Match(HttpContextBase httpContext,Route route,string parameterName,RouteValueDictionary values,RouteDirection routeDirection) {

        //do the database look-up here

        //return the result according the value you got from DB
        return true;
    }
}

我在我的应用程序上使用Ninject作为IoC容器,它实现了IDependencyResolver并且我注册了我的依赖项:

private static void RegisterServices(IKernel kernel) {

        kernel.Bind<ICountryRepository<Country>>().
            To<CountryRepository>();
    }

如何以依赖注入友好的方式使用此路由约束?

编辑

我找不到一种方法来传递这种依赖于单元测试:

[Fact]
public void country_route_should_pass() {

    var mockContext = new Mock<HttpContextBase>();
    mockContext.Setup(c => c.Request.AppRelativeCurrentExecutionFilePath).Returns("~/countries/italy");

    var routes = new RouteCollection();
    TugberkUgurlu.ReservationHub.Web.Routes.RegisterRoutes(routes);

    RouteData routeData = routes.GetRouteData(mockContext.Object);

    Assert.NotNull(routeData);
    Assert.Equal("Countries",routeData.Values["controller"]);
    Assert.Equal("Index",routeData.Values["action"]);
    Assert.Equal("italy",routeData.Values["country"]);
}

解决方法

routes.MapRoute(
    "Countries","countries/{country}",new { 
        controller = "Countries",action = "Index" 
    },new { 
        country = new CountryRouteConstraint(
            DependencyResolver.Current.GetService<ICountryRepository<Country>>()
        ) 
    }
);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读