简体   繁体   English

具有第 3 方依赖项的库设计和 DI

[英]Library design and DI with 3rd party dependencies

I'm writing a library for internal use.我正在编写一个供内部使用的库。 The purpose of this library is to abstract away calls to some internal REST API's.这个库的目的是抽象出对一些内部 REST API 的调用。 Under the hood, I'm using Flurl to make the requests.在后台,我使用 Flurl 来提出请求。 The library also provides extensions methods that sets up DI (Core Web) to easily wire everything together ( services.AddXYIntegration() ).该库还提供了设置 DI(Core Web)以轻松将所有内容连接在一起的扩展方法( services.AddXYIntegration() )。 In case of flurl, my library provides an implementation of DefaultHttpClientFactory (inherits from IHttpClientFactory ) => X509ClientFactory .在 flurl 的情况下,我的库提供了DefaultHttpClientFactory的实现(从IHttpClientFactory继承)=> X509ClientFactory To avoid collision or overwriting DI of applications using my library that probably also use Flurl for https requests and want to provide a custom implementation for IHttpClientFactory I created an empty interface just to "mark" my libraries implementation and use that in the DI wiring.为了避免使用我的库的应用程序的冲突或覆盖 DI,这些库可能还使用 Flurl 处理 https 请求并希望为IHttpClientFactory提供自定义实现,我创建了一个空接口,只是为了“标记”我的库实现并在 DI 接线中使用它。

Little bit code:一点点代码:

public interface IX509HttpClientFactory : IHttpClientFactory 
{
    // empty interface, violates CA1040
}

public class X509HttpClientFactory : DefaultHttpClientFactory /* inherits from IHttpClientFactory */, IX509HttpClientFactory
{
    // Implementation details...
}

So, instead of injecting X509HttpClientFactory for IHttpClientFactory , the library creates the instance for IX509HttpClientFactory .因此,库不是为IHttpClientFactory注入X509HttpClientFactory ,而是为IX509HttpClientFactory创建实例。 IHttpClientFactory is still "available" for injection. IHttpClientFactory仍然“可用于”注入。

My question is not specific to flurl, it's more a general question for similar scenarios.我的问题不是针对 flurl 的,而是针对类似情况的一般性问题。

Is this a good design?这是一个好的设计吗? How do you handle such cases where you have configurable 3rd party dependencies?您如何处理具有可配置的 3rd 方依赖项的这种情况? Is it a feasible scenario to violate CA1040.违反 CA1040 是否可行。

So, instead of injecting X509HttpClientFactory for IHttpClientFactory , the library creates the instance for IX509HttpClientFactory .因此,库不是为IHttpClientFactory注入X509HttpClientFactory ,而是为IX509HttpClientFactory创建实例。

If I'm understanding you correctly, then yes, I think this is the way to go.如果我对您的理解正确,那么是的,我认为这是通往 go 的方式。 DI is an application-level concept, and although we're conditioned to use it to instantiate most things, it's still totally appropriate to new up dependencies internal to a library in order to keep that library well encapsulated. DI 是一个应用程序级别的概念,尽管我们习惯于使用它来实例化大多数事物,但它仍然完全适合在库内部new依赖项以保持该库的良好封装。 I wouldn't even expose IX509HttpClientFactory publicly unless there's a need to that I'm not seeing.我什至不会公开公开IX509HttpClientFactory除非有我没有看到的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM