Question

We've been using Unity for our ASP.NET MVC3 applications. The configuration is done solely in the web.config file. See example below, where we are using singleton. We are using constructor injection. For 99% of our classes, we don't use singleton lifetime property. We are looking at our performance and found out that multiple instances of the same class was being built multiple times for the same request. We realized that instead of generating 3000 objects per request, we could knock it down to about 200 objects. We may have a bigger design issue but that is for another day. We are looking into making a good chunk of our unity class configurations to use singleton.

<typeAlias alias="singleton"
           type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
<type type="ITMSLogger" mapTo="TMSLogger">
    <lifetime type="singleton" />
    <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
    </typeConfig>
</type>

Questions:

  1. When marking the lifetime type to singleton, is that instance shared only for a specific user or all the user base?
  2. With marking these as singletons, do we need to setup synchronization on methods to avoid issues with a user performing multiple request at once?
  3. Anything else I should be aware of?
Was it helpful?

Solution

  1. A singleton instance is shared across the container instance. You should only have a single container instance in your application, so in effect, the singleton lifetime creates a globally shared instance.

  2. Yes, all singletons are potentially accessed by many threads, so they must be thread-safe.

  3. Yes, don't use XML to configure your container. Write a set of conventions instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top