Reputation: 5632
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.
Upvotes: 2
Views: 1604
Reputation: 32725
An IOC container is best used for creating components; but it shouldn't be used for creating model objects. For example, this is good:
public ActionResult SignUp(string username, string password)
{
var user = new User(); // Your model object
user.Username = username; //...
_repository.Save(user);
return Redirect(...);
}
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:
public ActionResult Show(int userId)
{
var user = _repository.Load<User>(userId);
var model = new ShowUserModel(user);
return View(model);
}
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:
class HomeController : Controller
{
readonly Func<IFooService> _fooServiceFactory;
public HomeController(Func<IFooService> fooServiceFactory)
{
_fooServiceFactory = fooServiceFactory;
}
public ActionResult SomeAction()
{
var service = _fooServiceFactory(); // Resolves IFooService dynamically
service.DoStuff();
}
}
Any decent IOC container should be able to handle Func<T>
injection.
Upvotes: 3
Reputation: 1038890
You don't use a DI container to resolve action arguments. That's what a model binder is intended to do in ASP.NET MVC. And by the way your actions should be taking any domain models as arguments => they should be taking only view models. View models are classes that are specifically defined to meet the requirements of a given view.
So for some specific cases you have the possibility of writing a custom model binder which will be responsible for the instantiation and binding of your action arguments. As far as the instantiation of the model binder itself is concerned, in ASP.NET MVC 3 you could use a dependency resolver which could be used to inject dependencies into this model binder using your DI framework of choice.
Upvotes: 3