2

I have one interface with 2 classes implementing it, I need to load each class but unity has:

m_unityContainer.Resolve() // Where is the interface IGeneric

my config looks like:

      <type type="IGeneric" mapTo="ClassA">
      </type>
      <type type="IGeneric" mapTo="ClassB">
      </type>

any ideas?

thanks

5 Answers5

2

You could also use a generic interface as follow:

public interface IGeneric{}

public interface IGeneric<T> : IGeneric{}

Then have a type safe resolution of the the interface:

container.RegisterType<IGeneric<ClassA>, ClassA>();
container.RegisterType<IGeneric<ClassB>, ClassB>();

ClassA classA = container.Resolve<IGeneric<ClassA>>();
ClassB classB = container.Resolve<IGeneric<ClassB>>();

Some interesting things start happening when you go down this road...

Schalk
  • 280
  • 1
  • 4
  • 13
1

This will give you all the registered classes that implement IGeneric.

IEnumerable<IGeneric> objects = container.ResolveAll<IGeneric>();
gcores
  • 12,376
  • 2
  • 49
  • 45
0

Here is a slightly different way. I am using Unity.2.1.505.2 (just in case that makes a difference).

  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>


      <unity>
        <container>
          <register type="IVehicle" mapTo="Car" name="myCarKey" />
          <register type="IVehicle" mapTo="Truck" name="myTruckKey" />
        </container>
      </unity>

Here is the DotNet code.

        UnityContainer container = new UnityContainer();

        UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
        section.Configure(container);


IVehicle v1 = container.Resolve<IVehicle>("myCarKey"); 

IVehicle v2 = container.Resolve<IVehicle>("myTruckKey"); 

See:

http://msdn.microsoft.com/en-us/library/ff664762(v=pandp.50).aspx

granadaCoder
  • 26,328
  • 10
  • 113
  • 146
0

I found out the solution, a name property has to be used in each entry:




and the code will look like obj= container.ResolveAll("ClassA");

0

Schalk - looks good. What would be the notation for specifying that in the Unity.config?