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

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

How to Determine if a Column Exists in a DataReader