How does ninject work at a high level, how does it intercept object instantiation?
Asked Answered
F

2

5

At a high level, how do these dep. injection frameworks work?

I can understand if you always instantiate an object via a custom factory like:

IUser user = DepInjector.Get<User>();

I'm guessing what happens is, wherever you defined the mappings, it will look at the type you want and try and find a match, if found, it will via reflection instantiate the type.

Are there dep. inj. frameworks that would work like:

IUser user = new User();

If so, how would it get the correct user, where is it hooking into the CLR to do this? In case of an asp.net website, is it any different?

Folger answered 30/5, 2011 at 17:3 Comment(0)
J
8

If you want to know how Ninject works then the obvious place to start would be reading How Injection Works on their official wiki. It does use reflection but it now also uses dynamic methods:

"By default, the StandardKernel will create dynamic methods (via System.Reflection.Emit.DynamicMethod) that can be used to inject values into the different injection targets. These dynamic methods are then triggered via delegate calls."

As for you second example, I don't believe there are any DI frameworks that would do what you ask. However, constructor injection tends to be most common way of implementing IoC, so that when a class is constructed it knows what type to bind to via some configuration binding. So in your example IUser would be mapped to concrete User in config bindings so that any consuming class that has an IUser parameter as part of its constructor would get the correct User type passed in.

Jargonize answered 30/5, 2011 at 17:36 Comment(1)
+1 but I'd link to this which explains that there's none of the magic the OP is assuming there might be pretty directlyMauricio
S
2

AFAIK there's no way to "hook into" object instantiation with the CLR. The only way to use DI in the second case would be to employ an assembly rewriter (i.e. a postprocessor similar to PostSharp) to replace the call to new with a call to the DI factory method (i.e. GetUser) in the compiled code.

Scirrhous answered 30/5, 2011 at 17:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.