user3575477
user3575477

Reputation: 31

How do I use Global instance class

hello sorry my english is not good,I hope you can understand me.. I'm using this DbEntities and other classes everywhere
How do I use this classes global? I don't want to create continuously instance, example Can I do this with single pattern? or global Constructor ? or What should I do?

thank you

 namespace Crewnetix.Entity.Concrete 
{
    public class Crew
    {
        DbEntities _DbEntities = new DbEntities (); >> object context db entities
        CertificateItem _Certificate = new CertificateItem ();
        WorldProcess _WorldProcess = new WorldProcess ();
        List<CertificateItem> _Certificates = new List<CertificateItem>();     
        CountryCity.CountryItem _Country = new CountryCity.CountryItem();

     }
}

  namespace Docnetix.Entity.Concrete
{
    public class Document
    {
        DbEntities _DbEntities = new DbEntities ();
        CertificateItem _Certificate = new CertificateItem ();
        WorldProcess _WorldProcess = new WorldProcess ();
        List<CertificateItem> _Certificates = new List<CertificateItem>();     
        CountryCity.CountryItem _Country = new CountryCity.CountryItem();

  }


  namespace accountingnetix.Entity.Concrete
{
    public class accounting
    {
        DbEntities _DbEntities = new DbEntities ();  
        CertificateItem _Certificate = new CertificateItem ();
        WorldProcess _WorldProcess = new WorldProcess ();
        List<CertificateItem> _Certificates = new List<CertificateItem>();     
        CountryCity.CountryItem _Country = new CountryCity.CountryItem();        
  }
}

example I want to it..I thought it

  namespace Global
{
    public static class GlobalInstance
    {
        public static object GetCreateInstance(object class); >> class name
        {
              ...code
            return newInstance;
        }    
    }     
  }
}

  namespace crewnetix
{
    public class crew
    {
       object instance = GetCreateInstance(CertificateItem) >> class name

    }     
  }
}

Upvotes: 0

Views: 366

Answers (2)

Meysam Tolouee
Meysam Tolouee

Reputation: 579

Singleton Is perfect for your goal:

//1) make your constructor private

//2) add this code:

private static Your_Class_Name _Instance;
public static Your_Class_Name Instance
{
    get
    {
        if (_Instance == null)
            _Instance = new Your_Class_Name();
        return  _Instance;
    }
}

Upvotes: 2

Lars Anundsk&#229;s
Lars Anundsk&#229;s

Reputation: 1355

You could make the classes static? and mark each member you also would like to be global / static , e.g:

public static class A 
{
  public static string GetSomething() 
  {
      // get something and return it
  }

  public static string AProperty
  {
      // getter and setter
  }
}

using the class;

A.GetSomething()
var a = A.AProperty;

you would not need to create an instance.

Upvotes: 1

Related Questions