IoC for a list of named objects

I'm looking for advice on this issue and the service locator and class naming conventions are a good solution (I try to avoid these anti-patterns) and potential implications.

An application has a set of objects that implement the same interface with a different name. For example:

 public interface IDog  {
      void Bark();
 }

 public class Pug: IDog {
      public void Bark() {
         // Pug bark implementation
      }
 }

 public class Beagle: IDog {
      public void Bark() {
         // Beagle bark implementation
      }
 }

      

In code, when you need an IDog, you only know the string name that is passed to you, such as "Pug" or "Beagle". In this case, the string may contain special characters (example:) <breed:pug />

There are several suggested solutions:

  • Using reflection, find the implementation you want where string name == implementation name.
  • Add an attribute for each class using reflection, where the attribute property is string == attribute. Ex [DogBreed ("Pug")]
  • Add Breed property to IDog interface. Inject IList into the factory class and ask it to find the matching dog. Ex.

    Private IList _dogs; Public DogFactory(IList<IDog> dogs) { _dogs = dogs; } Public IDog GetDog(string dogBreed) { return _dogs.First(x => x.Breed == dogBreed); }

1 and 2, use a service locator. 1 uses an implied naming convention that you will only know by seeing the reflection code. The 3rd concern is that all objects will be built in memory even if you only need one implementation.

I've personally leaned towards # 3 in the past. Object creation should be cheap. However, this is a legacy web application and the objects in the chain can have a significant initialization cost. This app uses Unity for IoC.

+3


source to share


1 answer


Option 1.

This parameter sounds like Partial Type Name Hint . Idiom. If you enter a candidate list and find an appropriate strategy among those candidates, this is just an old installer of the constructor and has nothing to do with Service Locator (which is good).

Option 2.

This parameter sounds like Metadata role identifier . Again, if you enter the candidate list via the constructor, the Service Locator will not be visible anywhere.

Option 3.



These parameters sound like a variation of the Role Interface Hint idiom. Still supports using the old old constructor installation.


Personally, I prefer the Partial Type Name Hint because this project does not affect the implementation of any business logic. All selection logic becomes pure infrastructure and can be defined independently for implementations and clients.

When it comes to the cost of constructing appropriate object graphs, there are ways to address any problems in clean ways .

+3


source







All Articles