Unity does not inject dependencies defined in the base class

I integrate Unity 2.0 into my ASP.NET application (using the UnityPageHandlerFactory approach) and everything works fine until I try to move one of the dependencies to the PageBase class, which will then be used by all pages. This property is never set when invoking BuildUp.

I am using the UnityPageHandlerFactory class described here, which uses the BuildUp (type, object) method to inject dependencies on each page when requested. As long as I have the properties defined in the declared type, the properties are introduced. But the properties defined in the base class are never set.

Is there anything else I need to do? It seems to me that this should be automatic.

+4
source share
2 answers

It turns out that I used another overload of the BuildUp method and moved on to fixing my problem in the above example.

I used BuildUp (object) and it did not work. When I switched to BuildUp (Type, object), everything works like a charm!

I'm not sure why, but I can only assume that it has something to do with how the type is allowed in the first overload, and not what happens when the type is explicitly specified.

In any case, this small change fixed all my problems.

+4
source

Can you show the relevant parts of the code? This is what I have, and it seems to work:

class InjectedClass { } class MyBase { [Dependency] public InjectedClass Dependency { get; set; } } class MyClass : MyBase { } class Program { static void Main(string[] args) { UnityContainer uc = new UnityContainer(); uc.RegisterType<InjectedClass>(); MyClass m = new MyClass(); uc.BuildUp(m); } } 

I also tested this with UnityPageHandlerFactory in an asp.net application and in a similar way I see that InjectedClass is being injected into my page, although the dependency property is in the base class.

+1
source

All Articles