I’m using IoC container for dependency injection in Asp.Net MVC 3 and everything seems perfect until I started to write Action methods in my controller. What is the best way to create entity/model objects within the action methods? Sometimes models are retrieved from certain repository or service which are injected to the controller via the constructor, but its not the case with many other model objects in the system.
I’m using IoC container for dependency injection in Asp.Net MVC 3 and everything seems
Share
An IOC container is best used for creating components; but it shouldn’t be used for creating model objects. For example, this is good:
A model object shouldn’t take any dependencies itself, so it shouldn’t need to be resolved from an IOC container. The same applies to view models:
After creation a model/view model should be effectively read-only, so any information it needs should be passed in via the controller – it shouldn’t take injected dependencies.
If you really, really did need to create components dynamically within the action, you can do it like this:
Any decent IOC container should be able to handle
Func<T>injection.