simpleinjector / SimpleInjector

An easy, flexible, and fast Dependency Injection library that promotes best practice to steer developers towards the pit of success.
https://simpleinjector.org
MIT License
1.22k stars 152 forks source link

Overload Collection.Append to add multiple registrations? #934

Closed Bouke closed 2 years ago

Bouke commented 2 years ago

Currently one can call Collection.Register only once per type. Calling twice will yield the following exception:

Mixing calls to Container.Collection.Register for the same open-generic service type is not supported. Consider making one single call to Container.Collection.Register(typeof(IValidator<>), types).

In a modular system it might be difficult to centralize all those registrations. We combine all registrations of a module into a single extension method like:

public static void AddModuleA(this Container container) {
    container.Register(...);
}

public static void AddModuleB(this Container container) {
    container.Register(...);
}

Now when using collections we can only call Collection.Register once. However we can call Collection.Append multiple times, which we can use from the extension methods shown above. I'm thinking of adding overloads to Append that take an assembly that is used to discover implementations and call Append for each type.

What do you think of such an approach? Am I overlooking an issue with this approach? Could it be something that SimpleInjector provides out of the box?

dotnetjunkie commented 2 years ago

I understand your concern I see how such overload would be helpful to you. There is currently no method with the behavior you are looking for. You either have to call Collection.Register once (with additional calls to Collection.Append) or callCollection.Append` multiple times.

Although it might be possible to add such overload, I feel that such overload would complicate the API and confuse future users, because it would become unclear what overload to call and why.

For now, I'd advise adding such extension method to your own code base. I'll keep an eye open to see if in the future similar requests come in from other users. If this is a problem that more users face, I have a better chance in defining the right API for this.