4

I have a large application which uses the old way of getting instances using ObjectFactory.GetInstance().

Now I want to move to application to the more correct way of injecting dependencies using constructor injection. However, it is almost impossible to convert all code at once (some static classes use ObjectFactory.GetInstance, other services do not have constructors with all dependencies, ...).

I was wondering if there is a way of replacing ObjectFactory.GetInstance calls with an replacement that uses the current nested container, e.g. replacing all ObjectFactory.GetInstance with Ioc.GetCurrentNestedContainer().GetInstance, to get it quickly up an running. But how would I could I implement Ioc.GetCurrentNestedContainer to return the currently active nested container?

I can not inject IContainer in all these classes (some are static or have no corresponding constructor), so they can not use constructor injection (yet).

DI is used in MVC, WCF, and Task based scenarios in this application.

julealgon
  • 7,072
  • 3
  • 32
  • 77
rekna
  • 5,313
  • 7
  • 45
  • 54

1 Answers1

2

Whilst I can't talk about WCF and task based scenarios, I can offer my recommendation for MVC (having spent time looking the options to a similar problem myself.

The solution to I've come across and ultimately settled for after seeing recommendations by StructureMap's creator, is to have a HttpContext bound nested container created on each request and stored within HttpContext.Items. From here you can reference the container by casting the instance stored within HttpContext.Items to an IContainer.

Infact, this is the same solution used within the StructureMap.MVC5 nuget package.

With this solution in mind, there's nothing to stop you replacing the ObjectFactory with with your own factory that returns the nested container from HttpContext.Items.

Update:

If HttpContext isn't available to you then the only other options I'm aware of is to create your own instance of the object factory that creates a new container and stores it in a Lazy<T> as suggested here and on the StructureMap's Google Groups page here.

I was going to suggest possiblity posting this question on the StructureMap Google Groups, but I see you've already done that. As an avid StructureMap user I'm keen to see what other suggestions arise from your post so I will be watching closely.

Community
  • 1
  • 1
Joseph Woodward
  • 9,191
  • 5
  • 44
  • 63
  • Unfortunately, the code (e.g. business layer) is used in both web, wcf, windows service scenario's, so the solution based on HttpContext is not sufficient. – rekna Dec 18 '14 at 06:23
  • Ok, I've just updated my answer for another possibility. Sorry I couldn't have been on more help! – Joseph Woodward Dec 18 '14 at 13:28
  • I think the biggest problem will be static classes and classes that are not created by DI. I just can't seem to find a way to get hold of the nested container. – rekna Dec 18 '14 at 22:08