【发布时间】:2011-06-13 21:16:48
【问题描述】:
我正在学习 TDD。我知道依赖注入,您可以将类的依赖项放在构造函数的参数中并传入它们,从默认构造函数传入默认实现,例如;
public AccountController() : this( RepositoryFactory.Users())
{
}
public AccountController( IUserRepository oUserRepository)
{
m_oUserRepository = oUserRepository;
}
RepositoryFactory 是一个简单的静态类,它返回为当前构建选择的实现
但默认的 ASP.NET MVC Web 应用程序项目并没有这样做,而是 DI 采用公共属性的形式,这些属性在测试类的对象初始化程序中分配,例如;来自 AccountController.cs :
protected override void Initialize(RequestContext requestContext)
{
if (FormsService == null)
{ FormsService = new FormsAuthenticationService(); }
if (MembershipService == null)
{ MembershipService = new AccountMembershipService(); }
base.Initialize(requestContext);
}
并且在测试类 AccountControllerTest.cs 中:
private static AccountController GetAccountController()
{
AccountController controller = new AccountController()
{
FormsService = new MockFormsAuthenticationService(),
MembershipService = new MockMembershipService(),
Url = new UrlHelper(requestContext),
};
//snip
}
所以现在我的 AccountController 类有两种依赖注入的方法。我应该使用哪一个?构造函数注入还是公共属性?
正在考虑构造函数注入...
ASP.NET MVC 使用公共属性是不是因为你需要提供一种特定的方式来注入构造函数,而基本的“新建”Web 应用程序需要通用作为起点?
【问题讨论】:
标签: c# asp.net-mvc dependency-injection tdd