在操作方法中使用IoC解析模型对象 [英] Using IoC to resolve model objects in Action Methods
问题描述
我在Asp.Net MVC 3中使用IoC容器进行依赖项注入,直到我开始在控制器中编写Action方法之前,一切似乎都很完美.在动作方法中创建实体/模型对象的最佳方法是什么?有时,某些模型是从某些存储库或服务中检索的,这些模型是通过构造函数注入到控制器的,但是系统中许多其他模型对象却不是这种情况.
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.
推荐答案
最好使用IOC容器来创建组件.但不应将其用于创建模型对象.例如,这是好:
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(...);
}
模型对象本身不应该具有任何依赖关系,因此不需要从IOC容器中对其进行解析.同样适用于视图模型:
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();
}
}
任何体面的IOC容器都应能够处理Func<T>
注射.
Any decent IOC container should be able to handle Func<T>
injection.
这篇关于在操作方法中使用IoC解析模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!