dependency-injectionspring.net

Spring.net ContextRegistry.GetContext fails with 2 interface implementations


I have a .net application, that uses Spring.net. Also there are 2 implementations of one interface. Which one should be used - it is based on configuration file.

The bootstrap for Spring has

<objects>
 <object id="Impl1" name="Impl1" type="namespace.Impl1, IInterface" >
  </object>
  <object id="Impl2" name="Impl2" type="namespace.Impl2, IInterface" >   
  </object>
</objects>

It fails on

var appContext = ContextRegistry.GetContext();

The error message is:

An unhandled exception of type 'System.Configuration.ConfigurationErrorsException' occurred in Spring.Core.dll

Additional information: Unsatisfied dependency expressed through constructor argument with index 2 of type [namespace.IInterface] : No unique object of type [namespace.IInterface] is defined : expected single matching object but found 2: System.Collections.Specialized.OrderedDictionary


Solution

  • I found another configuration, where autowire setting was set as autodetect.

    <object id="workspaceExportService" type="namespace.Imp3, Namespace"
              autowire="autodetect" />
    

    This class Imp3 has a constructor with IInterface parameter. So, It tries to resolve the implementation of IInterface, but find two of them.

    As a solution, you can add lazy-init="true" attribute to object node.