gpt4 book ai didi

c# - 使用 IoC 解析 Action Methods 中的模型对象

转载 作者:太空宇宙 更新时间:2023-11-03 19:25:58 24 4
gpt4 key购买 nike

我在 Asp.Net MVC 3 中使用 IoC 容器进行依赖注入(inject),一切看起来都很完美,直到我开始在我的 Controller 中编写 Action 方法。在操作方法中创建实体/模型对象的最佳方法是什么?有时模型是从某些存储库或服务中检索的,这些存储库或服务通过构造函数注入(inject)到 Controller 中,但系统中的许多其他模型对象并非如此。

最佳答案

IOC 容器最适合用于创建组件;但它不应该用于创建模型对象。例如,这是:

public ActionResult SignUp(string username, string password)
{
var user = new User(); // Your model object
user.Username = username; //...

_repository.Save(user);

return Redirect(...);
}

模型对象本身不应该有任何依赖关系,所以它不需要从 IOC 容器中解析。这同样适用于 View 模型:

public ActionResult Show(int userId)
{
var user = _repository.Load<User>(userId);

var model = new ShowUserModel(user);
return View(model);
}

创建模型/ View 模型后应该是有效的只读的,所以它需要的任何信息都应该通过 Controller 传递——它不应该采用注入(inject)的依赖关系。

如果你真的,真的需要在 Action 中动态创建组件,你可以这样做:

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>注入(inject)。

关于c# - 使用 IoC 解析 Action Methods 中的模型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8681150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com