Injecting Service in Middleware in ASP.NET Core

后端 未结 3 2062
孤街浪徒
孤街浪徒 2021-02-15 19:50

I want to inject a service based on the HTTP header value. So I have 2 classes - DbDataProvider and InMemDataProvider, both are implemented from IDataProvider. Whenever an API

3条回答
  •  孤街浪徒
    2021-02-15 20:26

    The answer above from Tsen is correct. You should implement a factory.

    But in addition you can also register factory methods to the services collection. Like so:

    Services.AddTransient(serviceProvider => serviceProvider.GetService().Create())
    

    This registers your IDataProvider. In the Create you should evaluate that HTTP header value so it returns the correct IDataProvider instance. Then in any class you need it you can simply request IDataProvider via the constructor and the correct implementation will be provided by the container.

提交回复
热议问题