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<>));
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.
Usually, I'd register my dependencies with parameters using 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
?
CodePudding user response:
You should be injecting your configuration class into your other dependencies' classes, and let them pick out what they want. What you're doing is breaking that separation of concerns.
CodePudding user response:
You should make use of the Options Pattern.
You need to bind the config to a class and register the class for DI. Then in the constructor for the class that needs the config, you pass it in via the constructor.
Documentation Here:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-6.0