MVC3 + Ninject - 如何实现?

16

我刚开始学习使用IoC容器,因此选择了Ninject。

经过几个小时的努力,我仍然无法弄清如何在我的MVC3应用程序中设置Ninject。

到目前为止,我已经做了以下工作:

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>();
    }
}

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);

    }
}

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());
    }

}

每次尝试加载索引视图时,它要么会抛出溢出异常,要么会出现HTTP 404错误 - 如果我删除所有的Ninject代码,它就能正常工作,出了什么问题?

1个回答

15
您正在将自己的依赖项解析器与MVC扩展混合使用。建议您选择自己的依赖项解析器或仅使用MVC扩展,而不是两者同时使用。当使用MVC扩展时,您必须使用OnApplicationStarted而不是Application_Start。
请参见http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/并查看随源代码一起提供的SampleApplication https://github.com/ninject/ninject.web.mvc
此外,如果您在构建服务器上使用当前版本,则不再使用该修复程序:http://teamcity.codebetter.com

更新: Ninject.MVC3 包继续更新,并且可以在 MVC4 RTM(和 RC)中直接使用。有关详细信息,请参见此wiki页面


我访问了您的链接以下载示例应用程序。它缺少文件并且无法编译。 - Christian Payne
2
@Christian Payne 一切都在那里。只需阅读如何操作!CI服务器确保它是可构建的。 - Remo Gloor
你需要使用OnApplicationStarted并继承自NinjectHttpApplication吗?我应该把我的旧代码void Global_PostReleaseRequestState(object sender, EventArgs e)public override void Init()void Global_PreRequestHandlerExecute(object sender, EventArgs e)放在哪里? - Maslow
API随着时间的推移发生了太多变化,尽管我可以说很多这些变化可能是由于MVC框架的更改所带来的。这是一个相当简单的概念,但我已经阅读了相互矛盾的文档和博客有一段时间了。 - user74754

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接