0

I'm playing around with some Dependency Injection (StructureMap) with my ASP.NET MVC application. Works great.

Becuase StructureMap is using DI via the most gready constructor (I hope I got that concept named right), I'm under the impression that it creates an instance of an object for each argument, in the most gready constructor.

So, is it possible to tell a DI framework (in this case, it's StructureMap but i'm curious if it can do it for any other .NET DI Framework) to NOT create the instance when the constructor is called, but to delay that object's construction until required?

Sorta like some lazy-object construction or something...

IAdapter
  • 62,595
  • 73
  • 179
  • 242
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
  • I'd be surprised if you can't. I found how to disable the default injection behaviour which might be useful if you cant find the 'by design' method: http://structuremap.sourceforge.net/FAQ.htm#FAQ11 – Matt Kocaj Oct 18 '09 at 09:12

2 Answers2

1

All di frameworks that support singleton->session/request scoped mappings typically instantiate a proxy object instead of the "real" object when a singleton object needs to access a session scoped object. Construction of the "real" instance is normally deferred to the first time a method on the proxy is invoked.

I believe castle windsor supports this mechanism.

krosenvold
  • 75,535
  • 32
  • 152
  • 208
0

Short answer: Yes, you can do this. Register your types using the .Net 4 Lazy<T> class like this:

x.For(typeof(Lazy<>)).Use(typeof(Lazy<>))
 .CtorDependency<bool>("isThreadSafe").Is(true);

For the long answer and explanation, see my answer to question 6811956. I think it will give you what you need. If you aren't using .Net 4 you'll have to implement your own Lazy<T> class to pull this off. See question 3207580 as a starting point.

Does Structuremap support Lazy out of the box?

Implementation of Lazy<T> for .NET 3.5

UPDATE: In StructureMap 3, "CtorDependency" has become just "Ctor", but otherwise seems to be working just the same.

Community
  • 1
  • 1
Mel
  • 2,337
  • 19
  • 25
  • This question wasn't asking about the specific Lazy type, so I think this anwer, while helpful, is a bit of a detour. The simplest answer is to just accept a Func in place of your constructor arguments. – Joshua Flanagan Sep 03 '11 at 00:27
  • He was asking whether it's possible to delay the creation of the objects, and I have shown how to do it using the Lazy class, since that is precisely what it is intended for. Accepting Func is just another way to accomplish the same thing, only now YOU are responsible for caching the results of the first execution so that you don't create a new copy every time you reference the Func. I find the Lazy class to be a clean way to avoid these problems, and so that is the approach I would recommend to solving the initial problem. – Mel Sep 06 '11 at 15:14