结束语一个API来支持依赖注入 [英] Wrapping an API to support dependency injection

查看:150
本文介绍了结束语一个API来支持依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与该只是有静态函数的API交互,并且不能打开和改变。

I am interacting with an API that just has static functions, and cannot be opened up and changed.

    public class WindowsNativeGraphAPI
    {
        public static IEnumerable<IGraphData> GetGraphData();
        public static bool DeleteGraphData(IGraphData data);
    }

我希望能够通过API到一个函数或构造,并遵守依赖注入(以防万一,我们换了API后)。

I would like to be able to pass the API into a function or constructor and comply with dependency injection (just in case we were to swap out the API later).

public void GatherGraphData(IGraphAPI api)
{...}

要允许此API传递中作为一个参数,我想至少需要抽象的使用接口传递到函数。

To allow this API to be passed in as a parameter, I'd need to at least abstract to use an interface to pass into the function.

    public interface IGraphAPI
    {
        IEnumerable<IGraphData> GetGraphData();
        bool DeleteGraphData(IGraphData data);
    }

不过,我需要实现另一个类的接口,因为我不能改变原来的API。这个类是围绕API一个轻量级的包装,只是调用的API相应的功能,并返回相同的结果。

However, I would then need to implement the interface in another class as I cannot change the original API. This class would be a lightweight wrapper around the API that just invokes the corresponding function on the API and returns the same result.

    public class WindowsGraphAPI : IGraphAPI
    {
        public IEnumerable<IGraphData> GetGraphData()
        {
            return WindowsNativeGraphAPI.GetGraphData();
        }

        public bool DeleteGraphData(IGraphData data)
        {
            return WindowsNativeGraphAPI.DeleteGraphData(data)
        }
    }

我不喜欢制造另一个类来包装API的想法。据我所知,这个包装是非常轻便,将只返回API的结果,但我怎么测试包装?该包装应可能还含有一些异常处理,以应付在API中的错误。如果我们要改变到另一个API,即遭遇了同样的问题,我们不得不重新创建这些额外的类和接口。

I don't like the idea of creating another class to wrap the API. I understand that this wrapper would be very lightweight and would just return the results of the API, but how do I test the wrapper? The wrapper should probably also contain some exception handling to cope with errors in the API. If we were to change to another API, that suffered the same problem, we'd have to create these extra classes and interfaces again.

理想情况下,最终结果将是一个mockable API,可以写入的单元测试消耗它的新组件时使用。

Ideally, the end result would be a mockable API that can be used when writing the unit tests for the new component that consumes it.

这是正确的方式做到这一点?能不能做到另一种方式?

Is this the proper way to do this? Can it be done another way?

感谢

推荐答案

是的,这是正确的方式。新的API接口和代理类封装的使用何种基础库的决定 - 一个责任

Yes, it's the proper way. The new API interface and proxy class encapsulate the decision of what underlying library to use - a single responsibility.

这篇关于结束语一个API来支持依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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