BuildUp Singletons at configuration time

Apr 3, 2009 at 1:12 PM
Hello,

is there a way to tell Unity, to build up singletons and resolving dependencies at configuration time?
Maybe using application code or Xml-Configuration.

I want to host an instance of a type as singleton in den UnityContainer, but i don´t want to
call Resove() or Resolve<T>() to build up the singleton. Because in my application code
i do not need an instance of that type.

The type i want to use and host as singleton, has dependencies to other types, but no type
has a dependency to that type.
Apr 6, 2009 at 2:45 AM
You can do it via the API, but not from the config file. All you need to do is:

IUnityContainer container = ... set up container here ...

container.BuildUp(MySingleton.Instance);

Out of curiousity, why do you want to manage it outside the container? You could just do:

container.Resolve<MySingletonType>()

Set it as container controlled lifetime and everything just works. Something must have a dependency on that type, otherwise, why do you have it at all?

Apr 7, 2009 at 10:27 AM
ErrorLogService is a singleton:
1- In typeAlias define what is a singleton
2- Set the lifetime element to singleton (the name matching with the singleton definition in 1) in your Component

<unity>
    <typeAliases>
      <!-- Lifetime manager types -->
      <typeAlias alias="singleton"
           type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
             Microsoft.Practices.Unity" />

      <typeAlias alias="external"
           type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,
             Microsoft.Practices.Unity" />
      <typeAlias alias="perThread"
           type="Microsoft.Practices.Unity.PerThreadLifetimeManager,
             Microsoft.Practices.Unity" />
    </typeAliases>
    <containers>
      <container name="production">
        <types>
          <type name="ErrorLogService"
                type="Acm.Esb.Service.ILogErrorService,Acm.Esb.Service"
                mapTo="Acm.Esb.Service.LogErrorService, Acm.Esb.Service">
            <lifetime type="singleton" />
          </type>
        </types>
      </container>
    </containers>
  </unity>