-3

I have a MVVM application, and I need to declare a variable somewhere and access it from everywhere in my assembly, that is, from different classes in different namespaces. I have tried to declare an internal variable in the main class but it does not work. Any ideas?

Willy
  • 9,848
  • 22
  • 141
  • 284

1 Answers1

1

Sounds like you want a simple "Service"

namespace en.my.services
{
     public class VariableService
     {
         public string SomeVariable {get; set;}
     }
}

Which you can inject where needed:

using en.my.services; // Make Service namespace known

namespace en.my.clients 
{
    public class MyServiceClient
    {
        VariableService svc = null;

        public MyServiceClient ( VariableService varsserv ) // <- Parameter-Injection via 
                                                            // your DI Framework
        {   
            svc = varserv;
        }

        public void SomeMethod()
        {
            svc.SomeVariable = "Update";
        }
    }
}

I'd recommend to also use an interface. So you can easily (unit-)test by mocking the interface. So, you'd have IVariableService and VariableService implementing it. The clients would take the interface and your DI Framework config would make the connection from the interface to a singleton instance of the implementation.

Fildor
  • 14,510
  • 4
  • 35
  • 67
  • Yes I have done it using interfaces and DI, but once you instantiate class MyServiceClient (MyServiceClient client = new MyServiceClient(new VariableService())) where VariableService is a class which has a constructor and implements an interface, then I need to have access to client variable everywhere from different classes placed in different namespaces. how to do this? – Willy Jan 25 '19 at 14:01
  • You can inject the Service class whereever you need it. Just tell your DI framework, it shall make it a singleton. Only mind, it won't be thread safe out of the box. – Fildor Jan 25 '19 at 14:02
  • I only need to inject it once, then use always the same variable 'Client' everywhere. – Willy Jan 25 '19 at 14:04
  • Then you have exactly the problem you have. Inject where needed. That's the idea behind that pattern. – Fildor Jan 25 '19 at 14:05
  • Yes, I know but I only inject it once because I do not need to inject it more times. It's a type of "Inicialisation". Then I would like to use the variable client everywhere because once injected nothing changes. Then through this variable I have access to a method that I use frequently everywhere. – Willy Jan 25 '19 at 14:12
  • I am aware of that. But as you obviously figured out: that won't work. – Fildor Jan 25 '19 at 14:17
  • 1
    ok, finally I have done what you suggested. I think it's the only way to do it. thx. – Willy Jan 25 '19 at 22:01