Thursday, April 11, 2013

Microsoft Unity IsRegister is for Debug only

This blog entry is based on this forum discussion, and of course my horrible experience with this.

So here was my code idea.

1 - Start off with an empty container.
2 - Whenever a Interface was asked to be resolved I would look on my current registered interfaces (aka using IsRegistered)
3 - If implementation was found just resolve it.
4 - If implementation was NOT found start looking on current directory for assemblies built by me (my assemblies would start with the company name)
5 - Load assembly and look for classes that implemented the interface I was looking for.
6 - If a specific name of a class was not given I would return the first class that implemented the interface asked.

Great code right? Not really, when running on a multi-threaded system I would get the follow error:

Exception:System.Exception: Collection was modified; enumeration operation may not execute.

So I started looking around and found the article mentioned above. Someone on the thread mentions that IsRegistered should only be used for Debug purpose. And it is NOT thread safe :(

Here is the code posted:

public static bool IsRegistered(this IUnityContainer container, Type typeToCheck, string nameToCheck)
        {
            Guard.ArgumentNotNull(container, "container");
            Guard.ArgumentNotNull(typeToCheck, "typeToCheck");

            var registration = from r in container.Registrations
                               where r.RegisteredType == typeToCheck && r.Name == nameToCheck
                               select r;
            return registration.FirstOrDefault() != null;
        }

The LINQ in there was my issue.

So I resorted to trying to do the register and if throw exception I catch and do my search.



try
{
    newItem = _container.Resolve(interfaceType);
}
catch (ResolutionFailedException)
{
   /// handle it here.

Have fun!

No comments:

Post a Comment

Kitematic - Self Signed Certificate In Certificate Chain

Found this issue while behind a enterprise proxy. Proxy uses self signed certificate. Windows has the certificate as trusted, docker works f...