【发布时间】:2012-01-02 10:20:07
【问题描述】:
对 DI 越来越熟悉,但我仍然有一些小问题。
阅读一些文章,上面写着“必须在入口点进行注入”
假设我有一种情况,我们有 wcf 服务,这些服务供内部 win/web 应用程序使用,而外部第三方使用这些 wcf 服务。
现在您在哪里注入服务和存储库? 以上对我来说似乎是一个常见的场景!
我还传递了所有这些接口。(非常适合模拟)我如何阻止某人从应该不调用存储库的层调用 EG 我的存储库。
EG 只有业务层应该调用 DAL。 现在,通过将 IRepository 注入控制器,开发人员可以调用 DAL。
有什么建议吗?清除所有这些的链接
我的可怜人 DI 的点头示例。我如何在 entryPoint 使用 unity 和 Injecting all 来做同样的事情?
[TestFixture]
public class Class1
{
[Test]
public void GetAll_when_called_is_invoked()
{
var mockRepository = new Mock<ICustomerRepository>();
mockRepository.Setup(x => x.GetAll()).Verifiable();
new CustomerService(mockRepository.Object);
ICustomerBiz customerBiz = new CustomerBizImp(mockRepository.Object);
customerBiz.GetAll();
mockRepository.Verify(x=>x.GetAll(),Times.AtLeastOnce());
}
}
public class CustomerService : ICustomerService //For brevity (in real will be a wcf service)
{
private readonly ICustomerRepository _customerRepository;
public CustomerService(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
public IEnumerable<Customer> GetAll()
{
return _customerRepository.GetAll();
}
}
public class CustomerBizImp : ICustomerBiz
{
private readonly ICustomerRepository _customerRepository;
public CustomerBizImp(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
public IEnumerable<Customer> GetAll()
{
return _customerRepository.GetAll();
}
}
public class CustomerRepository : ICustomerRepository
{
public IEnumerable<Customer> GetAll()
{
throw new NotImplementedException();
}
}
public interface ICustomerRepository
{
IEnumerable<Customer> GetAll();
}
public interface ICustomerService
{
IEnumerable<Customer> GetAll();
}
public interface ICustomerBiz
{
IEnumerable<Customer> GetAll();
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
谢谢
【问题讨论】:
-
我们过去只在代码中执行基于 DEBUG 的构建 DI。换句话说,生产从来没有使用过基于 DI 的代码。
-
@zenwalker 那么你已经在使用 DI 浪费了你的时间,使用它的最佳理由之一是你可以注入不同的模块进行开发、测试和发布,每个模块都单独测试。
-
是的,这就是我的意思。我们做 DI 只是为了测试目的,即调试模式。我们没有将它们作为我们生产代码的一部分(即发布模式)发送给客户。抱歉,如果之前不清楚。
标签: c# dependency-injection inversion-of-control