简体   繁体   中英

What controller Initialize function does ASP.Net MVC4

i am new in MVC and learning. here i am putting some code. so see first

public class HomeController : BaseController
    {
        private IProductRepository productRepository;
        private string strRouteValue;

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            strRouteValue = this.ControllerContext.RouteData.Values["method"].ToString();
            this.productRepository = Factory.Create(strRouteValue);
        }

        [HttpGet]
        public ActionResult Index(int id)
        {            
            productRepository.Get(id);
            return View();
        }

        [HttpPost]
        public ActionResult Index(Product model)
        {
            productRepository.Add(model);            
            return View();
        }       
    }

what Initialize function does ?

every one must say this is where people would init many object, if so then we can do it in constructor of controller too. so what is special about controller Initialize function ?

what is difference between controller Initialize function and controller constructor ?

Check the documentation for that method: MSDN: Controller.Initialize() :

Initializes data that might not be available when the constructor is called .

This method cannot be called directly. Override this method in order to provide additional processing tasks before any ActionResult methods are called , such as setting the thread culture or assigning a custom provider for TempData objects. If you override this method, call the base control's Initialize method.

And as I suggested on your previous twenty or so questions about MVC, Dependency Injection and controller instantiation: stop piecing together advice from poor blogposts and irrelevant answers on SO. Buy a decent MVC book and read it from cover to cover . Then do the same with a book about Unit Testing. You will never get a thorough understanding of things if you continue this way.

There is a difference between instantiating a controller and initializing it. Instantiating is moreover a .NET concept not MVC, so every class is automatically instantiated using default constructor. So, constructor is basically a concept of class whereas Initializing is concept of action method. We override Initialize() method in order to provide additional processing tasks before any ActionResult methods are called, such as setting the thread culture or assigning TempData objects etc....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM