Ninject using MVC2 and webforms

322 views
Skip to first unread message

Rody

unread,
Jul 1, 2010, 1:38:19 AM7/1/10
to ninject
I want to use Ninject in a project which combines ASP.Net webforms and
ASP.Net MVC. I'm using Ninject 2, but when I use
NinjectHttpApplication from Ninject.Web.Mvc it complains when I use
somethings like a PageBase that the Kernel is not created.

I have the following in the Global.asax and am unsure what to add.

public class MvcApplication : Ninject.Web.Mvc.NinjectHttpApplication
{
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
RegisterAllControllersIn(Assembly.GetExecutingAssembly());
}

protected override Ninject.IKernel CreateKernel()
{
return new StandardKernel(new ServiceModule());
}
}

Does somebody has this working somewhere who could share some thoughts
or code on this?

Rody

unread,
Jul 6, 2010, 9:57:33 AM7/6/10
to ninject
I can't be the only one to try this.
I'm sure somebody had this requirement in the past just as I did.

Sean Chambers

unread,
Jul 6, 2010, 1:04:31 PM7/6/10
to nin...@googlegroups.com
There is no way to do injection with webforms. There is no hooks for
you to bootstrap the page initialization so that you can resolve
instances using the kernel.

If you are wanting access to the kernel from within webforms instances
(whether pages or controls), the only way to do it is using a service
locator.

For testability, you can then use poor mans dependency injection using
the service locator to make it feel like DI and to create seams that
allow you to get mocks in there.

Does this answer your question?

Sean

> --
> You received this message because you are subscribed to the Google
> Groups "ninject" group.
> To post to this group, send email to nin...@googlegroups.com.
> To unsubscribe from this group, send email to ninject+u...@googlegroups.com
> .
> For more options, visit this group at http://groups.google.com/group/ninject?hl=en
> .
>

Nate Kohari

unread,
Jul 6, 2010, 1:11:20 PM7/6/10
to nin...@googlegroups.com
Rody,

Sean's correct, there's no easy way to do injection with WebForms -- however, I've hacked together an alternative using a shared base class that derives from Page. It looks roughly like this:

public abstract class PageBase : Page
{
  public IKernel Kernel { get; private set; }
  public PageBase() { Kernel = ...; }
  public void Page_Init() { Kernel.Inject(this); }
}

This will allow you to property and method injection on any pages that inherit from PageBase. Note that the constructor is incomplete -- you'll have to access the kernel in some static fashion. You should be able to read it from the HttpApplication somehow.


-Nate

Sean Chambers

unread,
Jul 6, 2010, 9:24:04 PM7/6/10
to nin...@googlegroups.com
that's a nifty trick using the inject method like that. Didn't know you could even do that. 

Thanks Nate 


Reply all
Reply to author
Forward
0 new messages