MVC3 + Ninject – 怎么样?
我刚开始玩IoC容器,因此选择了Ninject。
经过几个小时的汗水和眼泪,我仍然无法弄清楚如何使用Ninject设置我的MVC3应用程序。
到目前为止我有:
的Global.asax.cs
public class MvcApplication : Ninject.Web.Mvc.NinjectHttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { DependencyResolver.SetResolver(new MyDependencyResolver(CreateKernel())); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } protected override IKernel CreateKernel() { var modules = new [] { new ServiceModule() }; return new StandardKernel(modules); } } ServiceModule.cs internal class ServiceModule : NinjectModule { public override void Load() { Bind().To(); } }
MyDependencyResolver.cs
public class MyDependencyResolver : IDependencyResolver { private IKernel kernel; public MyDependencyResolver(IKernel kernel) { this.kernel = kernel; } public object GetService(System.Type serviceType) { return kernel.TryGet(serviceType); } public System.Collections.Generic.IEnumerable GetServices(System.Type serviceType) { return kernel.GetAll(serviceType); } }
GreetingService.cs
public interface IGreetingService { string Hello(); } public class GreetingService : IGreetingService { public string Hello() { return "Hello from GreetingService"; } }
TestController.cs
public class TestController : Controller { private readonly IGreetingService service; public TestController(IGreetingService service) { this.service = service; } public ActionResult Index() { return View("Index", service.Hello()); } }
每次我尝试加载索引视图时,它只是抛出溢出exception或HTTP 404错误 – 如果我删除所有Ninject代码它完美地工作,什么是错的?
您正在将自己的依赖项解析器与MVC扩展混合使用。 我建议要么使用自己的依赖解析器,要么使用MVC扩展,但不能同时使用。 使用MVC扩展时,您必须使用OnApplicationStarted而不是Application_Start。
请参阅http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/并查看MVC扩展源代码附带的SampleApplication https://github.com/ninject/ninject.web.mvc 。
当您使用构建服务器的当前版本时,也不再使用此修复程序: http : //teamcity.codebetter.com
更新: Ninject.MVC3
包继续更新,并针对MVC4 RTM(和RC)工作OOTB。 有关详细信息,请参阅Wiki中的此页面 。
- 使用ASP.NET MVC操作方法
- NewtonSoft Json DeserializeObject空Guid字段
- appSettings和ConfigurationManager.AppSettings问题
- 动态添加字段到Razor表单
- 哎呀! 为什么System.Web.Mvc.HandleErrorInfo会传递给我的视图?
- NHibernate.LazyInitializationException
- ASP.NET MVC网站在任何浏览器上都被重定向到本地IIS而不是IIS express
- 从MVC 4 Web Api返回匿名类型失败,出现序列化错误
- ASPNET MVC – 使用具有相同签名的新助手覆盖Html.TextBoxFor(model.property)?