引用 vs 依赖 [英] Reference vs Dependency

查看:32
本文介绍了引用 vs 依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题之后,我现在有以下结构:

Following on from this question, I now have the following structure:

Wolfie.Core - 包含业务逻辑和实体,还包含存储库接口(例如 IUserRepository) 需要访问存储库的类使用构造函数注入.

Wolfie.Core - Contains business logic & entities, also contains repository interfaces (eg IUserRepository) Classes that need to access the repository are using constructor injection.

Wolfie.Data - 引用 Wolfie.Core 并有一个实现 IUserRepository 的 UserRepository

Wolfie.Data - References Wolfie.Core and has a UserRepository implementing IUserRepository

所以到目前为止我很满意.Core 对数据实现一无所知,因此不依赖任何东西.

So I'm happy with this so far. Core doesn't know anything about data implementation and therefore isn't dependent on anything.

我遇到的绊脚石是在我的 Web 层.

The stumbling block I get to is in my Web layer.

我的 Web 项目引用了我的 Core 项目.然后我可以新建一个核心类,比如 User,但我必须将 IUserRepository 的具体实现传递给它.所以我需要在我的Web项目中引用我的Data项目,这似乎是错误的.现在看起来 Web 也依赖于数据,这不应该如此.

My Web project references my Core project. I can then new up a Core class, say User, but I have to pass a concrete implementation of IUserRepository into it. So I need to reference my Data project in my Web project, which seems wrong. It now also looks like Web is dependent upon Data, which it shouldn't be.

那么,如何在不直接引用数据的情况下将我的核心用户类注入到数据类中?

So, how can I inject my Core User class with the Data class withouth directly referencing Data?

期待您的帮助.

推荐答案

您可以绑定到主应用程序代码中的接口,仅引用合同程序集(核心"程序集).然后使用反射在运行时加载您的依赖项并注入具体类.

You can bind to interfaces in your main application code, referencing only the contract assembly (the "Core" assembly). Then use reflections to load your dependencies at runtime and inject the concrete classes.

有几个问题需要解决:

  • 您将如何找到必要的程序集?
  • 找到程序集后,您应该使用哪些具体类?
  • 您将如何松散地配置您的应用程序以使用这些程序集和那些具体类?您不想简单地将硬编码的程序集引用和具体的类引用转换为硬编码的程序集和类名字符串...

这些问题可以通过许多不同的方式解决,并且是不同依赖注入库之间的主要区别因素之一.

These problem can be solved in many different ways, and are one of the main differentiating factors between different Dependency Injection libraries.

有些使用顶级配置代码或配置代码模块(例如 NInject),有些使用 XML 配置(例如例如 Unity),有些使用基于属性/约定的自动发现机制(例如 MAF/MEF),有些使用所有这些的组合(例如 Castle.Windsor).

Some use top-level configuration code or configuration code modules (for example NInject), some use XML configuration (for example Unity), some use an automatic discovery mechanism based attributes/conventions (for example MAF/MEF), and some use a combination of all of these (for example Castle.Windsor).

大多数或所有这些库都支持每种机制,但我已经提到了最突出的重点.

Most or all those libraries support each mechanism, but I've mentioned the most prominent focus.

这篇关于引用 vs 依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆