ebb*_*ebb 16 c# asp.net-mvc ninject inversion-of-control
我刚开始玩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<IGreetingService>().To<GreetingService>();
}
}
Run Code Online (Sandbox Code Playgroud)
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<object> GetServices(System.Type serviceType)
{
return kernel.GetAll(serviceType);
}
}
Run Code Online (Sandbox Code Playgroud)
GreetingService.cs
public interface IGreetingService
{
string Hello();
}
public class GreetingService : IGreetingService
{
public string Hello()
{
return "Hello from GreetingService";
}
}
Run Code Online (Sandbox Code Playgroud)
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());
}
}
Run Code Online (Sandbox Code Playgroud)
每次我尝试加载索引视图时,它只是抛出溢出异常或HTTP 404错误 - 如果我删除所有Ninject代码它完美地工作,什么是错的?
Rem*_*oor 15
您正在将自己的依赖项解析器与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中的此页面.
| 归档时间: |
|
| 查看次数: |
17240 次 |
| 最近记录: |