DefaultControllerFactory和GetControllerInstance的Main函数是什么?

时间:2015-01-29 15:53:43

标签: c# asp.net-mvc-3 ninject

我正在学习MVC3并且正在阅读这本书" pro asp.net MVC3框架"我已经阅读了一些关于DefaultControllerFactory的文章,以及如何使用ninject作为de DI。 DefaultControllerFactory正在创建一个将使用ninject的新控制器吗?这是否意味着这个新的控制器将被称为evertytime你调用一个新的控制器,如ProductController:Controller?

我阅读下面的ninject文章,但它非常基本。下面的例子比较复杂,所以如果有人能解释一下它会有很多帮助!非常感谢你提前,我希望它也能帮助别人。

Step by Step Using Ninject for Dependency Injector

对于DefaultControllerFactory:

Controller lookup and default controller factory

Product.cs

namespace SportsStore3.WebUI.Controllers
{
public class ProductController : Controller
{
    private IProductsRepository repository;

    public ProductController(IProductsRepository productRepository)
    {
        repository = productRepository;        
    }
}

Infrastructure.cs

namespace SportsStore3.WebUI.Infrastructure
{
public class Infrastructure
{
    public class NinjectControllerFactory : DefaultControllerFactory
    {
        private IKernel ninjectKernel;

        public NinjectControllerFactory()
        {
            ninjectKernel = new StandardKernel();
            AddBindings();
        }
        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            return controllerType == null
                ? null
                : (IController)ninjectKernel.Get(controllerType);
        }

        private void AddBindings()
        {           
            ninjectKernel.Bind<SportsStore3.Domain.Abstract.IProductsRepository>().To<EFProductRepository>();             
        }
    }
}
}

EFProductRepository.cs

namespace SportsStore3.WebUI.Concrete
{
public class EFProductRepository : IProductsRepository{
     private EFDbContext context = new EFDbContext();

    public IQueryable<Product> Products{
        get {return context.Products;}
    }           
}
}

IProductRespository.cs

namespace SportsStore3.Domain.Abstract
{
 public interface IProductsRepository
{
     IQueryable<Product> Products { get; }
}
}

Products.cs

namespace SportsStore3.Domain
{
public class Product
{
    public int ProductID {get; set;}
    public string Name { get; set; }

}
}

的Global.asax.cs

 protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        ControllerBuilder.Current.SetControllerFactory(new SportsStore3.WebUI.Infrastructure.Infrastructure.NinjectControllerFactory()); ;
    }

0 个答案:

没有答案