The proper way to use UnityContainer? Newbie ask

Topics: General discussion
Jun 12, 2010 at 7:05 PM
Edited Jun 12, 2010 at 7:11 PM

Let's say I have class A, B and C
A depends on B
B depends on C

I'd declared like this

Public Class A
    Private _b As B
    <Dependency()> Public Property B() As B
        Get
            Return _b
        End Get
        Set(ByVal value As B)
            _b = value
        End Set
    End Property
End Class

Public Class B
    Private _c As C
    <Dependency()> Public Property C() As C
        Get
            Return _c
        End Get
        Set(ByVal value As C)
            _c = value
        End Set
    End Property
End Class

Public Class C
End Class

What I expect is whenever I created an instance of A.
There should be an instance of B and C automatically created consequently.
Firstly I wrote something like

Dim Container = New UnityContainer
Container.RegisterType(Of C)(New InjectionFactory(Function(c) New C))
Container.RegisterType(Of B)(New InjectionFactory(Function(c) c.Resolve(Of B)()))
Dim myA = Container.Resolve(Of A)()


But the code above causes StackOverflowException.
I don't know how to fix it.
Lastly I have to write code like this

Dim Container = New UnityContainer
Dim myC = New C
Container.RegisterInstance(GetType(C), myC)
Dim myB = Container.Resolve(Of B)()
Container.RegisterInstance(GetType(B), myB)
Dim myA = Container.Resolve(Of A)()
Which looks very smell and seems pointless to use UnityContainer.
So can somebody show me the proper way to write it?
Thanks.
Jun 16, 2010 at 1:39 AM
Edited Jun 16, 2010 at 1:40 AM

An infinite loop occurs because of this:

Container.RegisterType(Of B)(New InjectionFactory(Function(c) c.Resolve(Of B)()))

What happens is that when it's trying to resolve for B, it repeatedly calls it causing an infinite loop.  I assume you do that because when using InjectionFactory, the dependencies of the type you're registering won't get injected when resolving, am I right?  You need to properly register type B with the necessary dependencies.

BTW, Please post Unity questions in the Unity forum.

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com