C# DI with generic interface and parameters

Viewed 97

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?

2 Answers

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.

Related