title: Service Locator style lookup in Spring.Net - better ideas?
body: <p>I'm using the following method to get objects from the Spring.Net context by type when I expect to have only one so I don't need to put magic strings in my code. I've seen this area come up in profiles as potentially slow there. Is there a less brute force and better way for me to be doing this?</p>
  
  <pre><code>public static T Locate&lt;T&gt;()
  {
      var objList = Context.GetObjectsOfType(typeof(T));
      if (objList.Count == 0)
          throw new Exception("No object of type: " + typeof(T).FullName + " found");
      if (objList.Count &gt; 1)
          throw new Exception("Multiple objects of type: " + typeof(T).FullName + " found");
      T oneObj = default(T);
      foreach (DictionaryEntry e in objList)
          oneObj = (T)e.Value;
      return oneObj;
  }
  </code></pre>
  
  <p>At times I also use this style to pass in run-time parameters. Before someone jumps on me for the anti-pattern... as far as I can tell doing a service locator type pattern is the only way to pass in parameters whose values are only known at runtime.</p>
  
  <pre><code>public static T Locate&lt;T&gt;(params object[] arguments) where T : class
  {
      var objectNames = Context.GetObjectNamesForType(typeof(T));
      if (objectNames.Length == 1)
      {
          return Context.GetObject(objectNames[0], arguments) as T;
      }
      if (objectNames.Length == 0)
      {
          throw new ApplicationException("No object of type: " + typeof(T).FullName + " found");
      }
      throw new ApplicationException("Multiple objects of type: " + typeof(T).FullName + " found");
  }
  </code></pre>