Don't Do This With Microsoft's Unity IoC Container

I recently did something pretty dumb when using Microsoft's Unity IoC container. Because one of my classes depended on a string parameter for its constructor (a configuration value that I pass into it), I had to register the type rather than simply relying on dependency chaining. See below (this code is an example of the real code, but not the actual code as to protect my employer's intellectual property guidelines):

.RegisterType<IProjectRepository, ProjectRepository>(
     new InjectionConstructor(
        new ResolvedParameter(typeof(IRESTServiceHelpers)),
            ConfigurationManager.AppSettings["CentralServiceURL"],
        new ResolvedParameter(typeof(ICacheManager)),
        new WidgetFactory()))

See the problem? It's that "new WidgetFactory()" statement. The real class in question didn't implement an interface, so, like a dummy, I set it up to be injected by Unity as shown above.

Mistake!!!

What the code above ends up doing is maintaining a single, new WidgetFactory object that it uses for each instance of ProjectRepository that it spins up. In essence, it acts like a singleton.

To correct this issue, I changed the code to look like the following:

.RegisterType<IProjectRepository, ProjectRepository>(
     new InjectionConstructor(
        new ResolvedParameter(typeof(IRESTServiceHelpers)),
            ConfigurationManager.AppSettings["CentralServiceURL"],
        new ResolvedParameter(typeof(ICacheManager)),
        new ResolvedParameter(typeof(WidgetFactory))))

Because Unity is smart enough to resolve the instance by the concrete type, using a ResolvedParameter instead of newing up an instance directly was the way to go. Lesson learned!

Comments

Popular posts from this blog

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

"$.ajax is not a function" Error When Using jQuery and Darren Johnstone's ASP.NET Upload/Download Module v2