Is type being injected ?

Dec 6, 2009 at 3:18 PM
Edited Dec 6, 2009 at 3:19 PM



Please consider the following code:


    interface IA { }

    interface IB { }

    class A : IA


    class B : IB
        public B(IA a)


    class Tester
        public static void Main(string[] args)
            var container = new UnityContainer();

            container.RegisterType<IA, A>();
            container.RegisterType<IB, B>();

            var a = container.Resolve<IA>();
            var b = container.Resolve<IB>();


Is there any way to know if "IA" is being resolved by explicitly calling resolve or is it being injected into the injection constructor ?

How can I intercept the creation of "IA" when its being injected into "IB" ?



Dec 6, 2009 at 5:46 PM

There's no way to know why the object's being created. Could you be more specific about what you're trying to do? There's probably several other ways to accomplish it.



Dec 7, 2009 at 7:48 AM

Well I'll try to explain.

When IA is being injected into IBs' constructor it's needs to be an existing instance that is being held in some kind of cache. In other words the IA that needs to be injected into IBs' ctor needs to be an existing instance (based on some kind of logic) and not a new instance.

I thought about using a static factory for the creation of IB,, however IBs' interface is actually a little different from what was posted above. It's actually IB<T> where T : class. Therefore using a static factory (using the static factory extension) would require more lines of code when registering types into the unity container. Let's say I have a IPerson class and an IEmployee interface then I would have to register each one separately like this:


and also


And that's because there's no overload for register factory that has a type to build as a parameter.


Thanks for the help.