我从 MVC3 开始,想使用一些灵活的架构,所以我阅读了数十篇博客,一本书(Pro ASP.NET MVC 3),阅读了有关 SOLID 原理的内容,最后得到了我喜欢的应用程序结构(或在至少我是这么认为的,到目前为止,因为我还没有在它上面构建任何东西):
在这个结构中:
域使用服务的主要原因是验证 POCO (IValidatable) 类的 Validate 方法上的唯一键。
我开始使用这种结构构建一个引用应用程序,但到目前为止,我遇到了两个问题:
我在这里想要实现的是能够从 EF 切换到 DAPPER 之类的其他东西,只需更改 DATA 程序集即可。
更新
现在(截至 2011 年 8 月 9 日)Ninject 正在工作,但我想我错过了一些东西。
我有一个带有两个构造函数的 CustomerRepository:
public class CustomerRepository : BaseRepository<Customer>, ICustomerRepository
{
// The repository usually receives a DbContext
public CustomerRepository(RefAppContext context)
: base(context)
{
}
// If we don't receive a DbContext then we create the repository with a defaulte one
public CustomerRepository()
: base(RefApp.DbContext())
{
}
...
}
在 TestInitialize 上:
// These are for testing the Repository against a test database
[TestInitialize()]
public void TestInitialize()
{
// Context used for tests
this.context = new RefAppContext();
// This is just to make sure Ninject is working,
// would have used: repository = new CustomerRepository(context);
this.kernel = NinjectMVC3.CreateKernel();
this.kernel.Rebind<ICustomerRepository>().To<CustomerRepository>().WithConstructorArgument("context", context);
this.repository = kernel.Get<ICustomerRepository>();
}
在客户类上:
public class Customer : IValidatableObject
{
...
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// I want to replace this with a "magic" call to ninject
CustomerRepository rep = new CustomerRepository();
Customer customer = rep.GetDupReferenceCustomer(this);
if (customer != null)
yield return new ValidationResult("Customer \"" + customer.Name + "\" has the same reference, can't duplicate", new [] { "Reference" });
}
...
}
在这种情况下使用 Ninject 的最佳方法是什么?
任何帮助将不胜感激。
答案,类似于
到目前为止,我将考虑这个问题。我可以让 Ninject 正常工作,但看起来实现 SOLID 的依赖倒置原则 (DIP) 需要更多时间。
在这方面,我不得不将域、服务和数据混为一谈,我将在其他时间创建另一个问题,并让项目暂时按照通常的方式进行。
谢谢大家。
最佳答案
单元测试应该在没有 Ninject 的情况下完成。只需创建一个被测对象的实例并手动为每个依赖项注入(inject)一个模拟。
对于集成测试,您可以使用内核,包括来自应用程序 Bootstrap 和 的所有绑定(bind)。重新绑定(bind) 您想用 Mock 替换的所有内容。例如将 session 绑定(bind)替换为使用内存数据存储而不是真实数据库的绑定(bind)。
关于asp.net-mvc-3 - 在 SOLID 应用程序架构中使用 Ninject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6920371/