Search code examples
asp.net-mvc-2c#-4.0ninject-2ninject-extensions

MVC2 & Ninject2 - Controllers not resolving dependency


I foolishly decided to try something new on a Friday job!

So I have used NuGet to add Ninject.Web.Mvc 2.2.x.x to my .Net MVC2 project.

I've altered my Global.asax.cs

using System.Web.Mvc;
using System.Web.Routing;
using IntegraRecipients;
using Mailer;
using Ninject;
using Ninject.Web.Mvc;
using Ninject.Modules;

namespace WebMailer
{

public class MvcApplication : NinjectHttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("favicon.ico");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Mail", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

    protected override void OnApplicationStarted()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterRoutes(RouteTable.Routes);
    }

    protected override IKernel CreateKernel()
    {
        return new StandardKernel(new INinjectModule[] { new MailModule()});
    }

    internal class MailModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IMailing>().To<Mailing>();
            Bind<IMailingContext>().To<MailingContext>();
            Bind<IRecipientContext>().To<RecipientContext>();
        }
    }
}

}

and I've created a controller like so...

using System.Linq;
using System.Web.Mvc;
using WebMailer.Models;

namespace WebMailer.Controllers
{
    [ValidateInput(false)]
    public class MailController : Controller
    {
        private readonly IMailingContext _mailContext;
        private readonly IRecipientContext _integraContext;

        public MailController(IMailingContext mail,IRecipientContext integra)
        {
            _mailContext = mail;
            _integraContext = integra;
        }

        public ActionResult Index()
        {
            return View(_mailContext.GetAllMailings().Select(mailing => new MailingViewModel(mailing)).ToList());
        }
    }
}

But the controller is still insisting that

The type or namespace name 'IRecipientContext' could not be found (are you missing a using directive or an assembly reference?)

and

The type or namespace name 'IMailingContext' could not be found (are you missing a using directive or an assembly reference?)

My google-fu has failed me and I really hope this is just a silly typo/missing line thing

Thanks in advance

P


Solution

  • Ninject does not change the way assemblies are compiled! It deos not magically add references to other assemblies or add using directives. If you are using interfaces from other assemblies you have to add a using directive and a reference to this assembly.

    All Ninject is about is to wire up your application at runtime.