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

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

问题描述

假设我想在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天全站免登陆