简体   繁体   English

C# 具有通用接口和参数的 DI

[英]C# DI with generic interface and parameters

Given a generic interface and its implementation:给定一个通用接口及其实现:

public interface IGenericInterface<T> { ... }

public class GenericImplementation<T> : IGenericInterface<T> { ... }

I am registering this for DI using services.AddTransient(typeof(IGenericInterface<>), typeof(GenericImplementation<>));我正在使用services.AddTransient(typeof(IGenericInterface<>), typeof(GenericImplementation<>));为 DI 注册这个

This works fine, of course.当然,这很好用。 But I would like to inject a setting/config from the appsettings.json , which is where I'm coming unstuck.但我想从appsettings.json注入一个设置/配置,这就是我要解开的地方。

Usually, I'd register my dependencies with parameters using services.AddTransient<IInterface>(x => new Implementation(x.GetRequiredService<IDependency>(), configuration["SomeSetting"]);通常,我会使用services.AddTransient<IInterface>(x => new Implementation(x.GetRequiredService<IDependency>(), configuration["SomeSetting"]);来注册我的依赖项。

Is it possible to pass parameters to a dependency when registering it by type ?type注册时是否可以将参数传递给依赖项?

You should make use of the Options Pattern.您应该使用选项模式。

You need to bind the config to a class and register the class for DI.您需要将配置绑定到 class 并为 DI 注册 class。 Then in the constructor for the class that needs the config, you pass it in via the constructor.然后在需要配置的 class 的构造函数中,通过构造函数传入它。

Documentation Here:文档在这里:

https://learn.microsoft.com/en-us/as.net/core/fundamentals/configuration/options?view=as.netcore-6.0 https://learn.microsoft.com/en-us/as.net/core/fundamentals/configuration/options?view=as.netcore-6.0

You should be injecting your configuration class into your other dependencies' classes, and let them pick out what they want.您应该将您的配置 class 注入到您的其他依赖项的类中,并让他们选择他们想要的。 What you're doing is breaking that separation of concerns.您正在做的是打破关注点分离。

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

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