How do I create an instance without calling resolve?

Oct 9, 2009 at 1:04 PM
Edited Oct 9, 2009 at 1:06 PM

Hi,

I would like to be able to create instances of objects through xml config that don't have a direct dependency.

For example, I have the following pseudo code:

interface IMessageParserService
{
  void RegisterParser(IMessageParser messageParser);
  void Parse(IMessageData data);
}

class MessageParserA : MessageParserBase { }

class MessageParserB : MessageParserBase { }

class MessageParserService : IMessageParserService { }

In the config I would define something like:

                    <type name="ExchangeRateParser" 
                          type="IMessageParser"
                          mapTo="WinterClient.Modules.Refreshment.Market.Messages.ExchangeRateParser, WinterClient.Modules.Refreshment.Market">
                        <lifetime type="singleton" />
           
<type name="ParserA" 
      type="IMessageParser"
      mapTo="MessageParserA, Something.A">
  <lifetime type="singleton" />
</type>
<type name="ParserB" 
      type="IMessageParser"
      mapTo="MessageParserB, Something.B">
  <lifetime type="singleton" />
</type>

<type type="IMessageParserService, Something.Services"
      mapTo="MessageParserService, Something.Services">
  <lifetime type="singleton" />
</type>

I want to be able to register MessageParserA and MessageParserB with the MessageParserService. The way I was planning on doing this was to have the message parsers resolve the MessageParserService and call RegisterParser. This way if I need to support a new parser I can just add it in.

The way I've got round this is to do the following:

 

<type type="IMessageParserService, Something.Services"
      mapTo="MessageParserService, Something.Services">
  <lifetime type="singleton" />
  <typeConfig>
    <method name="Add">
      <param name="listOfParsers" parameterType="string">
        <value value="MessageParserA,MessageParserB" />
      </param>
    </method>
  </typeConfig>                        
</type>

The add method of the MessageParserService then loops through calling resolve to get the list of parsers to hold internally. This works fine, but I'd still like to know if there's a way of getting Unity to create an instance of MessageParserA and MessageParserB without me calling Resolve?

 

 

 

Dec 18, 2009 at 1:41 AM

Change the Add method so that it takes an array of IMessageParsers. It has to be an actual array, not a List<> or IEnumerable<>. When you do this, the container will under the hood call ResolveAll on that type and give you all of them.