tags:

views:

135

answers:

1

I was previously using SM 2.5.3. I had some code that stored a named instance of an object that looked like this:

ObjectFactory.Configure(x => 
        x.ForRequestedType<T>()
         .TheDefault.IsThis(item)
         .WithName(itemName));

Then to request one of the items from the container, I would do:

return ObjectFactory.GetNamedInstance<T>(key);

If the particular named instance wasn't in the container, this would blow up and I caught the exception and returned null. This was how I could tell if something had been put in the container yet or not (was using it for caching small pieces of data).

However, I updated the code to 2.6 yesterday, and now it always returns an instance of whatever "T" is, even if the named instance does not exist in the container. Even the new TryGetInstance() method does this. So my question is, how do I tell if the named instance is NOT in fact in the container? I noticed that retrieving non-named instances does not behave this way.

This is what my new registration code looks like:

ObjectFactory.Configure(x => x.For<T>().Use(item).Named(itemName));

If anyone can tell me what I'm doing wrong, or has a better suggestion for doing this, I'd really appreciate it!

A: 

I found a solution. When retrieving the named instance from the container, I now use the features of the Model object to check if the named instance is there:

        if (ObjectFactory.Model.InstancesOf<T>().Any(x => x.Name == itemName))
        {
            return ObjectFactory.GetNamedInstance<T>(itemName);
        }

        return default(T);

This also allows me to get rid of the try...catch block that I had before, which is a good thing. Still, if anyone has any other suggestions, I'd like to hear them. Thanks!

Dan Jensen