Theoretically, the only the place to use a DI container is in the setup of the project. in the case of an ASP.NET MVC project, that would be in the Global.asax's Application_Start method. For my project, I am using a NInject based ControllerFactory to instantiate controllers as needed, and then the controllers have whatever dependencies they need in their constructors so NInject hooks them up appropriately.
my global.asax:
private static IKernel kernel = new StandardKernel();
protected void Application_Start()
{
kernel.Bind<IRepository<User>>().To<NHibernateRepository<User>>();
ControllerBuilder.Current.SetControllerFactory( new NinjectControllerFactory( kernel ) );
}
and my NInjectControllerFactory:
public class NinjectControllerFactory : System.Web.Mvc.DefaultControllerFactory
{
private IKernel container;
public NinjectControllerFactory( IKernel container )
{
this.container = container;
}
protected override IController GetControllerInstance( RequestContext requestContext, Type controllerType )
{
if ( controllerType != null )
{
IController controller = container.Get( controllerType ) as IController;
Check.Require( controller, "Could not instantiate controller type: {0}", controllerType.FullName );
return controller;
}
return base.GetControllerInstance( requestContext, controllerType );
}
}