如何避免与IoC容器耦合 [英] How to Avoid Coupling with an IoC Container

查看:62
本文介绍了如何避免与IoC容器耦合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用DI和IoC开发可扩展框架.用户必须能够通过将自己的实现拖放到容器中来覆盖框架中的现有功能.

I'm in the process of developing an extensible framework using DI and IoC. Users must be able override existing functionality within the framework by dropping their own implementations into the container.

如何允许用户执行此操作而不要求他们知道我使用的是哪个IoC容器?

How can I allow users to do this without requiring them to know which IoC container I am using?

我当前的中途解决方案是按如下方式构造程序集:

My current half-way solution is to structure my assemblies as follows:

1)定义仅包含接口的抽象程序集.

1) Define abstract assemblies containing only interfaces.

2)定义实现这些接口的具体程序集.用户可以定义自己的功能来覆盖现有功能.

2) Define concrete assemblies which implement these interfaces. Users may define their own to override existing functionality.

3)在单独的程序集中定义容器绑定;即每个混凝土组件一个绑定组件.

3) Define the container bindings in separate assemblies; i.e. one binding assembly per concrete assembly.

这意味着具体组件未与特定的IoC容器耦合,如果我使用其他容器,它们将被关闭以免更改.但是,仍然需要用户知道我的框架正在使用哪个容器来编写绑定程序集,并且如果我更改了IoC容器(即从Ninject改为Spring),他们将需要释放新的绑定程序集.

This means the concrete assemblies are not coupled with a particular IoC container, and they would be closed against change if I used a different container. However, users are still required to know which container my framework is using in order to write the binding assemblies, and they would need to release new binding assemblies if I changed the IoC container (i.e. from Ninject to Spring).

我想念什么吗?

推荐答案

公共服务定位器是一种方法,但它仅包含用于解析的方法,而不用于注册.

Common Service Locator is one approach, but it only contains methods for resolving, not for registering.

您可能想看看在 agatha-rrsl项目中是如何实现的. 此处,这里有更完整的解释,但是简而言之:

You may want to have a look at how this is implemented in the agatha-rrsl project. There's a more complete explanation here, but in short:

  • 定义一个与容器无关的接口,用于注册和解析类型
  • 为不同的容器提供实现(或让用户提交实现)

注意事项:您可能无法直接在库中使用所选的容器.

Caveat: you probably won't be able to directly use your container of choice in your library.

这篇关于如何避免与IoC容器耦合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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