【发布时间】:2011-12-15 17:48:36
【问题描述】:
我目前正在开发一个使用 MVC3 的 Web 应用程序。 MVC3 项目通过服务层访问我们的应用程序逻辑。服务层使用通过 UnitOfWork 模式访问的存储库访问数据库。
我刚刚安装了 StructureMap 来负责将我的服务注入到 MVC3 项目中。示例控制器如下所示
public class AccountManagementController : Controller
{
IAccountService accountService;
public AccountManagementController(IAccountService accountService)
{
this.accountService = accountService;
}
现在,我的问题是我的 AccountService 类需要在创建结构映射时注入 UnitOfWork。目前我通过拥有 2 个控制器来处理这个问题。一个接受一个接口,另一个实例化一个具体的类。
public class AccountService : IAccountService, IDisposable
{
private IUnitOfWork unitOfWork;
internal AccountService(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
public AccountService()
{
this.unitOfWork = new UnitOfWork();
}
这对我来说似乎是代码异味。有没有更正确的方法来处理这个问题?
谢谢, 弗里兹
【问题讨论】:
-
删除默认构造函数...
-
我觉得多年来配置StructureMap的流畅界面已经发生了变化,所以我不知道具体什么代码适用于什么版本。但是如果需要,您应该能够告诉您的引导程序代码使用特定的
IUnitOfWork实现。看这里:stackoverflow.com/q/289512/328193 -
谢谢,我去看看。这需要从我的网站上引用我的 DAL,我通常会尽量避免。
-
但是对引用 DAL 的应用层的引用实际上是相同的。另外:让应用程序根引用并配置/连接整个应用程序并没有错。
标签: asp.net-mvc-3 dependency-injection