简体   繁体   English

Autofac 工作单元中的依赖注入

[英]Dependency Injection in Unit of work with Autofac

Im going through a tutorial which uses EF 6 and a UnitOfWork pattern.我正在阅读使用 EF 6 和 UnitOfWork 模式的教程。 The idea is to introduce Autofac and im not entirely sure how i should convert this line of code so it fits in with the project to introduce Dependency Injection这个想法是引入 Autofac,我不完全确定我应该如何转换这行代码,以便它适合引入依赖注入的项目

    private readonly ContactsContext _context;
    public UnitOfWork(ContactsContext context)
    {
        _context = context;
        Customers = new CustomerRepository(_context);
    }
   
    public ICustomerRepository Customers { get; }

I cant change我无法改变

Customers = new CustomerRepository(_context);

to

Customers = new ICustomerRepository(_context);

(Note the Interface) as it throws an error. (注意接口),因为它会引发错误。

I can post the ICustomerRepository if required but i dont know how i should be handling the dependency in this case?如果需要,我可以发布 ICustomerRepository 但我不知道在这种情况下我应该如何处理依赖项?

I can post more code if required but i didnt know if this is enough and im missing something simple or not?如果需要,我可以发布更多代码,但我不知道这是否足够,我是否遗漏了一些简单的东西?

The standard way to do this would be to take a constructor dependency on ICustomerRepository instead of instantiating a CustomerRepository yourself within the constructor:执行此操作的标准方法是采用对ICustomerRepository的构造函数依赖,而不是在构造函数中自己实例化CustomerRepository

    private readonly ContactsContext _context;
    public UnitOfWork(ContactsContext context, ICustomerRepository customerRepository)
    {
        _context = context;
        Customers = customerRepository;
    }
   
    public ICustomerRepository Customers { get; }

Of course, you will also need to register CustomerRepository with Autofac as the implementation of ICustomerRepository .当然,你还需要注册CustomerRepository与Autofac作为实施ICustomerRepository

builder.RegisterType<CustomerRepository>().As<ICustomerRepository>();

This means that you will be relying on Autofac to create the repository instead of doing so yourself (Autofac will 'know' to inject the ContactsContext into the constructor of CustomerRepository ).这意味着您将依赖 Autofac 来创建存储库,而不是自己创建(Autofac 将“知道”将ContactsContext注入CustomerRepository的构造函数中)。 That's the pervasive aspect of dependency injection - it ends up requiring you to adopt it all the way down .这就是依赖注入的普及方面-它最终需要你通过它一路下跌

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM