todo依赖注入的时间和地点.你能澄清一下吗?

use*_*969 2 c# dependency-injection inversion-of-control

越来越熟悉DI,但我仍然没有多少琐事.

阅读几篇文章,其中写着"必须在入口点进行注射"

假设我有一种情况,我们有wcf服务,这些服务由内部win/web应用程序使用,外部第三方使用这些wcf服务.

现在,您在哪里注入服务和存储库?我上面似乎是一个常见的场景!

此外,我通过所有这些接口左右.(为嘲弄非常好)如何从从应该一层叫EG我的仓库停止有人被调用的库.

EG只有业务层应该调用DAL.现在通过将IRepository注入控制器,没有什么能阻止开发人员调用DAL.

有什么建议吗?清除所有这些的链接

我的穷人DI的Noddy例子.如何使用unity并在entryPoint注入所有内容?

[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; }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Seb*_*ber 5

这是关于Composition根的博客文章,或者你称之为入口点的博客文章.它来自Mark Seemann,它是.NET依赖注入的作者.如果您正在寻找对DI的深刻理解,那么这本书是必读的.

关于如何组合WCF和DI,有很多样本.如果您在IIS中托管服务,则需要编写自定义ServiceHostFactory来初始化DI容器.这是微软Unity的一个示例.

至于

如何阻止某人从不应该调用存储库的层调用EG我的存储库

你是否使用穷人的DI并通过你所有的层传递你所有的参考?那么你一定要考虑使用像StructureMap,Castle Windsor,AutoFacUnity这样的DI/IoC容器.

如果你问"我怎么能一般地避免某人不遵循我的图层边界的情况":如果程序集引用另一个不应该引用的程序(例如UI不应该引用DAL),则编写失败的测试.


UPDATE

我假设您希望该服务使用ICustomerBiz而不是ICustomerRepository.如果这是正确的,Unity的设置将如下所示:

[TestMethod]
public void GetAll_with_Unity()
{
  var container = new UnityContainer();
  container.RegisterType<ICustomerRepository, CustomerRepository>();
  container.RegisterType<ICustomerBiz, CustomerBizImp>();
  container.RegisterType<ICustomerService, CustomerService>();
  var svc = container.Resolve<ICustomerService>();
  var all = svc.GetAll();
  Assert.AreEqual(1, all.Count());
}
Run Code Online (Sandbox Code Playgroud)