create a Multiton LifetimeManager

Jul 2, 2008 at 5:22 PM
Edited Jul 2, 2008 at 5:22 PM
Ola!

I try to create a Multiton Lifetimemanager, but my Unity Container returns everytime the same Object. I think he put only one Object and returens this.

My Code:
namespace UnityLifetimeManager
{
    public class MyMultitonLifetimeManager : LifetimeManager
    {
        private int counter = 3;
        private List<object> value = new List<object>();

        public override object GetValue()
        {
            if (value.Count != 0)
            {
                if (value.Count < counter)
                {
                    return value[value.Count - 1];
                }
                else
                {
                    System.Random ran = new System.Random();
                    int c = ran.Next(counter - 1);
                    return value[c];
                }
            }
            return null;

        }

        public override void SetValue(object newValue)
        {
            if (value.Count < counter)
            {
                value.Add(newValue);
            }
        }
        public override void RemoveValue()
        {
            //
        }
    }
}

Can somebody help me to correct my code?

Many Thanx,

telly

Jul 2, 2008 at 5:32 PM
If GetValue returns non-null, the build process is short-circuited and that value is returned as the result of the buildup.

This code:

              if (value.Count < counter)
                {
                    return value[value.Count - 1];
                }

always returns a value as soon as value.Count is greater than zero. As a result, as soon as you have one value, you'll always return that one and SetValue will never be called again.

Basically, you need to rethink the whole thing. ;-)


It looks like you want some kind of object pooling - is that what you're aiming for here?
Jul 2, 2008 at 9:45 PM
yes, i look for an object pool.....

There is now the question how to implement this....have you any ideas?

And at which time the container (or who) call the Remove Value Method.....and who can the lifetimemanager realize which Item of my List should be removed?

I change my GetValue to:
-------------------------------------
public override object GetValue()
        {
           if (counter == 3)
              {
                    System.Random ran = new System.Random();
                    int c = ran.Next(counter - 1);
                    return value[c];
               }
           else
              {
                    counter++;
                    return null;
              }
        }
-------------------------------------
But now there is no lazy loading (all object are created at first call) and like i describe above i dont know how to delete a Value. Can you help me?


Greetz and Thanx,

telly