0

VB.NET 2010, Framework 3.5

Question / problem with global scope in a Windows Service

Barebones Window Service with two default Classes, Class1 and Class2

Class1 looks like this.

Public Class Class1
    Public Hi As String = "Hi"
End Class

The main Service Class 'OnStart' below. obj1 looks like it should have global scope

Public Class Service

    Public obj1 As New Class1 ' need obj1 to have global scope

    Protected Overrides Sub OnStart(ByVal args() As String)

    End Sub
End Class

However, trying to access the global obj1 within Class2 generates the error "obj1 is not declared. It may be inaccessible due to its protection level"

Public Class Class2
    Public Sub SayHi()
        MsgBox(obj1.Hi) ' error here, obj1 is out of scope
    End Sub
End Class

In a non-Service app, where Sub Main replaces Sub OnStart, obj1 is visible everywhere. All the other classes can see obj1 until flow goes out of Sub Main.

Does anyone know how to get around this?

Rose
  • 641
  • 7
  • 17

1 Answers1

2

This only works in a non service app if the Sub Main is in a module.

The best solution is probably to create a separate class with a shared member

Public Class CommonObjects
    Public Shared obj1 As New Class1
End Class

Then you can use obj1 like this:

Public Class Class2
    Public Sub SayHi()
        MsgBox(CommonObjects.obj1.Hi)
    End Sub
End Class

Alternatively just create a module and put Public obj1 As New Class1 in it to use the object without having to specify the fully qualified name

See the answers to this question Classes vs. Modules in VB.NET for more information before deciding which route to take

Community
  • 1
  • 1
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
  • I was trying to avoid a module (feels like leftover remains from VB6 hehe) but it does seem most practical for what I have. – Rose Jan 29 '14 at 18:22