依赖注入 - 谁拥有接口? [英] Dependency Injection - Who owns the Interface?

查看:34
本文介绍了依赖注入 - 谁拥有接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想在 AOP 方法中使用依赖注入框架,目标是生成代码模块.共享接口所有权的最佳实践是什么?所有权是指为了使用接口而需要引用的代码体.

Assuming I want to use a dependency injection framework in an AOP approach, with the goal of producing code modules. What's the best practice for the ownership of the shared interfaces? By ownership I mean the body of code that needs to be referenced in order to use the interface.

我的第一个猜测是,在 AOP 中,您将定义一个接口类库,按方面命名空间.例如:company.aspect.logging.ILogger.然后,每个模块将引用该库,并避免在实现 ILogger 中涉及的任何代码也定义 ILogger.

My first guess is that in AOP you would define a class library of interfaces, namespaced by aspect. eg: company.aspect.logging.ILogger. Each module would then reference this library and avoid having any code involved in implementation of ILogger also define ILogger.

最佳做法?

推荐答案

定义接口类库是一个好的开始.这为您提供了最大的灵活性,因为您可以完全独立地改变所有消费者和所有实施者.

Defining a class library of interfaces is a good start. That gives you the ultimate in flexibility because you can vary all consumers and all implementers completely independently of each other.

这种方法的缺点是,如果您的接口本身会像这样导出其他接口:

The disadvantage of this approach is that if your interfaces themselves export other interfaces like this:

public interface IMyInterface
{
    IMyOtherInterface DoStuff();
}

您可能需要编写大量映射代码来从接口填充具体类(或者您可以使用 AutoMapper).

you may need to write a lot of mapping code that can populate concrete classes from the interfaces (or you can ause AutoMapper).

如果您只有一个消费者但有多个实现者,您可以通过与消费者(永远不会与实现者)一起定义接口来为自己节省一些这种映射,但会失去一些灵活性.但是,您仍然可以独立于消费者改变实施者,但不能反过来.

If you only have one consumer but several impelementers, you can save yourself some of this mapping by defining the interfaces together with the consumer (never with the implementer), but you lose some of the flexibility. However, you can still vary the implementers independently of the consumer, but not the other way around.

这篇关于依赖注入 - 谁拥有接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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