Search code examples
c#mvvminternals

Access a variable from different classes that are in different namespaces


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?


Solution

  • 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.