Parameter issue when creating instance

Mar 4, 2010 at 9:09 PM

Hi guys,

I have a beginner's question. Let's say I have the following classes:

public abstract class Animal
{
    protected string _name;
}

public class Dog:Animal 
{
  public Dog ( string name)
  {
      _name = name;
  }
}

public class Bird:Animal
{
  public Bird ( string name)
  {
      _name = name;
  }
}

public class SportsTeam 
{
   private string _name;
   private Animal _mascot;

   public SportsTeam ( string teamName, Animal mascot )
  {
      _name = teamName;
      _mascot = mascot ;
  }

   
}


Let's now say that I want to create 2 new teams:
Team: "ABC" with a dog mascot called "Pluto" and
Team: "EFG" with a bird mascot called "Birdie".

From what I understand, if I want to achieve my goal using Unity I would have to hard-code the teams and mascot names in the configuration file. Is that correct?
If not, can somebody tells me correct way to do it?

Thanks in advance for any attention.


Mar 8, 2010 at 1:24 AM

Yes, you'll specify the names explicitly in the config file.  You could also do it using the API but does the fact of hard-coding it in the configuration file really your issue?  If not, could you explain what really is it that you want to accomplish?

 

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

Mar 8, 2010 at 1:46 PM

Hi Sarah,thanks for the reply. My issue is indeed the fact of hard-coding the parameters in the configuration file. If during the execution of my program I have to instantiate 25 team objects, that's 50 values I have to hard-code in the config. The file gets blotted really fast.

Can you please provide me a code snippet of how to do it using the API?

 

Thanks for your help.

Mar 8, 2010 at 5:06 PM

This isn't really doable with Unity 1.2. In that case, what I'd suggest doing is creating a TeamFactory object, which has dependencies on the services you need, and has a Create method which takes the variable parameters. Then get the factory out of the container instead of trying to get Teams out directly.

In Unity 2.0 we added the ParameterOverride feature specifically to support this scenario, but there's still a lot of value in using explicit factories in cooperation with the container.

 

Mar 8, 2010 at 5:21 PM

Thanks for the reply ctavares. It makes much more sense now.