Controller Constructor called on Child Action
In my MVC3 app I am using some child actions (RenderAction()) to populate 2 p开发者_高级运维arts of my view. This helps me keep the code more modular and reusable. The problem is that the controller constructor is getting called again for each child action.
In my controller constructor I make a few calls to the database to get user data. They aren't expensive calls but when each child action has to make the same call it starts to add up. I'm sending duplicate queries off to the database for the same HTTP request.
Is this normal behavior? Should I stay away from child actions?
Yes - this is normal behaviour. Child actions go through the entire ASP.NET MVC processing pipeline, just like regular actions.
If you want to avoid this, then use a Partial View. Of course, this way you'll lose the ability to perform logic in your child action.
If your saying your "calling a few child actions", and "each action makes the same call to get user data", i think you need to do some refactoring. Maybe you could put this "user data" call in a child action, and apply output caching. If your talking about the "current user data", then you might be able to also stick it in the forms authentication ticket, and skip the DB call altogether. Hard to give more advice without knowing more about the situation.
The other point i'd make is why are you making database calls in a constructor? This is very bad practice. Use the constructor for instantiating members and setting up dependencies, not retrieving data.
精彩评论