简体   繁体   English

Asp.net核心2.0条件DI

[英]Asp.net core 2.0 Conditional DI

I have an interface that has 2 implementation IMYService MyServiceA MYServiceB 我有一个接口,有2个实现IMYService MyServiceA MYServiceB

Here the Implementation is dependent on some data in the request header used by the construtor of the Services like If Header has value of internalId then use MyServiceA and pass that Id to the services in constructor while if the value is missing use MyServiceB where as this service construct does not expect id. 这里的实现依赖于服务构造者使用的请求头中的一些数据,例如,如果Header具有internalId的值,则使用MyServiceA并将该Id传递给构造函数中的服务,而如果缺少该值,则使用MyServiceB作为此服务构造不期望id。

My Controller is defined with DI for IMyservice 我的控制器使用DI定义IMyservice

In general, you need a factory. 一般来说,你需要一个工厂。 That's generally a separate class that is responsible to managing instances of a particular similar type of thing and returns the appropriate instance based on some sort of convention or condition. 这通常是一个单独的类,负责管理特定类似事物的实例,并根据某种约定或条件返回适当的实例。 For example, if you've used IHttpClientFactory , you've see one in action. 例如,如果您使用过IHttpClientFactory ,则会看到其中一个正在运行。

Since the implementation depends on the request, you can cheat a little by using the "factory" overload of AddScoped : 由于实现取决于请求,您可以通过使用AddScoped的“factory”重载来AddScoped

services.AddScoped<IMyService>(p => 
{
    // return either MyServiceA or MyServiceB
});

The p param of the lambda is actually a scoped instance of IServiceProvider , so you can do stuff like pull out IHttpContextAccessor to look at the request details. lambda的p param实际上是IServiceProvider的作用域实例,因此您可以执行诸如拉出IHttpContextAccessor来查看请求详细信息。

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

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