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):
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:
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!
.RegisterType<IProjectReposito ry,
ProjectRepository>(
new
InjectionConstructor(
new
ResolvedParameter(typeof(IREST ServiceHelpers)),
Config urationManager.AppSettings[" CentralServi ceURL"],
new
ResolvedParameter(typeof(ICach eManager)),
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<IProjectReposito ry,
ProjectRepository>(
new
InjectionConstructor(
new
ResolvedParameter(typeof(IREST ServiceHelpers)),
Config urationManager.AppSettings[" CentralServi ceURL"],
new
ResolvedParameter(typeof(ICach eManager)),
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
Post a Comment