Dependency is not injected

Topics: CAB & Smart Client Software Factory
Aug 17, 2006 at 5:34 AM
originally posted by: AmanAnwari

Hi,

I'm new to CAB and object builder, understands DI

I was working with Object builder, created two classes ClassA (with default constructor) and ClassB (with constructor accepting ClassA reference, marked with constructor injection attribute), i was expecting ClassB to get previously created ClassA reference present in the locator's weak reference dictionary.

Here is the code

--------------------------------
Public Class ClassA

Public id As String

Public Sub New()
id = System.Guid.NewGuid.ToString
End Sub

End Class
--------------------------------

Public Class ClassB

Private m_o As DefaultConstructorType

Public Sub New()

End Sub

<InjectionConstructor()> _
Public Sub New(ByVal dep As ObjectBuilderTutorials.DefaultConstructorType)
m_o = dep
End Sub

End Class

--------------------------------

-----Test code-------------

Dim bld As New Builder
Dim loc As New ObjectBuilder.Locator

Dim a1 As Object = bld.BuildUp(loc, Type.GetType("ObjectBuilderTutorials.ClassA"), Nothing, Nothing)
Dim b1 As ClassB = bld.BuildUp(Of ClassB)(loc, "y", Nothing)

Current result b1 gets a new instance of ClassA and not a1.
Expected result: b1 getas instance a1

If this results are right then how do i achieve my expected results without creating ClassA as singleton?

Thanks
Aug 17, 2006 at 9:09 PM
originally posted by: mamu300B

Hi,

you have to add your newly created item to the locator.

And in C# your code would like this:

Builder bld = new Builder();
IReadWriteLocator loc = new Locator();

object a1 = bld.BuildUp(loc, typeof(ClassA), null, null);

loc.Add(new DependencyResolutionLocatorKey(typeof(ClassA), null), a1);

ClassB b1 = bld.BuildUp<ClassB>(loc, "y", null);

Hope this helps
-Matthias
Aug 18, 2006 at 2:15 PM
originally posted by: AmanAnwari

Yep, thanks it works