tags:

views:

398

answers:

1

Hi,

i have the following code, and when i try to run it, i can see that the BrokerProvider is not being resolve. here is my code + config:

 static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            UnityConfigurationSection section = (UnityConfigurationSection) ConfigurationManager.GetSection("unity");
            section.Containers.Default.Configure(container);

            new TestBroker().RunTestBroker();

        }



class TestBroker
    {
        private IBrokerProvider brokerProvider;

        public void RunTestBroker()
        {
            List<IPortfolio> portfolios = BrokerProvider.GetPortfolios();
        }

        [Dependency]
        public IBrokerProvider BrokerProvider
        {
            get { return brokerProvider; }
            set { brokerProvider = value; }
        }
    }



 <unity>
    <typeAliases>
      <typeAlias alias="string" type="System.String, mscorlib" />
      <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
      <typeAlias alias="IBrokerProvider" type="PA.Common.Interfaces.IBrokerProvider, PA.Common" />

      <typeAlias alias="PManager" type="PA.BrokerProviders.PManager, PA.BrokerProviders" />
    </typeAliases>
    <containers>
      <container>
        <types>
          <type type="IBrokerProvider" mapTo="PManager">
            <lifetime type="singleton" />
          </type>
        </types>
      </container>
    </containers>
  </unity>

another question: do i need to repeat the same 3 lines of code that i have under main in every other class that i would like to use unity or setting it up once is enough?

Thanks for the help

+2  A: 

That's because are creating TestBroker directly by calling operator new on it:

new TestBroker().RunTestBroker();

In order for unity to resolve your dependencies you need to call the framework like so:

var broker = container.Resolve<TestBroker>();

IUnityContainer is the interface that is going to be doing all the work for you - i.e. resolving types to instances. You only need to create it once and then just pass it around the application where ever you need it.

Igor Zevaka
thanks; do i need to map TestBroker in the configuration file too?
Or A
Yes, you do need to add it to the config section.
Igor Zevaka