Solved

Need help understanding "Activator.CreateInstance" (ASP.NET 2.0 / C#)

Posted on 2007-11-15
4
1,162 Views
Last Modified: 2013-11-07
I'm trying to get this concept because I want to use it. Bascially the end result is having an interchangable data access layer (Switching from SqlClient to OracleClient for example). Below is the core code that I'm trying to understand:

      static public ArticlesProvider Instance
      {
         get
         {
            _instance = (ArticlesProvider)Activator.CreateInstance(Type.GetType(DAL.SqlClient.SqlArticlesProvider));
            return _instance;
         }
      }

I found this snippet on the web but it's incomplete and couldn't find the rest of it. What I don't understand is what does Activator.CreateInstance do and is this really saying that it creating an instance of an entire namespace?
0
Comment
Question by:bemara57
  • 2
4 Comments
 
LVL 29

Expert Comment

by:anarki_jimbel
Comment Utility
From msdn (http://msdn2.microsoft.com/en-us/library/system.activator.createinstance(vs.80).aspx)
Activator.CreateInstance Method

Creates an instance of the specified type using the constructor that best matches the specified parameters.

Not sure about ASP.

E.g., in Remoting it may means thta no server instance is created before first clien call. You do not create an object by calling constructor but rather ask activator to get an instance. Srver object may be different type so the problem is that the *type* of object to create isn't know until runtime.  Activator helps to solve the problem.
0
 

Author Comment

by:bemara57
Comment Utility
Thanks but I can't get it to work in my website. Here's what I did but don't understand what the problem is:

namespace Company.DAL
{
    public abstract class ConfigProvider
    {
        static private ConfigProvider _instance = null;
        static public ConfigProvider Instance
        {
            get
            {
                if (_instance == null)
                    _instance = (ConfigProvider)Activator.CreateInstance(
                       Type.GetType(Company.DAL.MdbClient.MdbConfig));
                return _instance;
            }
        }

        public abstract string GetConfigValue(ConfigXML site, string id, string name);
    }
}

Then in the "interchangable" data access layer I have this:
namespace Company.DAL.MdbClient
{
    public class MdbConfig : ConfigProvider
    {
        public override string GetConfigValue(ConfigXML site, string id, string name)
        {
            try
            {
                string connString = WebConfigurationManager.ConnectionStrings[site.SettingsTable.ConnectionStringName].ConnectionString;
                string sqlCmd = "SELECT Value FROM " + site.SettingsTable.TableName + " WHERE UCASE(id)='" + id.ToUpper() + "' AND UCASE(name)='" + name.ToUpper() + "'";

                using (OleDbConnection conn = new OleDbConnection(connString))
                {
                    OleDbCommand cmd = new OleDbCommand(sqlCmd, conn);
                    conn.Open();

                    object obj = cmd.ExecuteScalar();

                    if (obj.Equals(System.DBNull.Value))
                        return string.Empty;
                    else
                        return (string)obj;
                }
            }
            catch
            {
                return string.Empty;
            }
        }
    }
}

Then in my aspx page I'm calling the method like this:
ConfigProvider.Instance.GetConfigValue(domain, "company", "Address1");

But I get this error:
Compiler Error Message: CS0119: 'Company.DAL.MdbClient.MdbConfig' is a 'type', which is not valid in the given context
Source Error:
Line 21:                 if (_instance == null)
Line 22:                     _instance = (ConfigProvider)Activator.CreateInstance(
Line 23:                        Type.GetType(Company.DAL.MdbClient.MdbConfig));
Line 24:                 return _instance;
Line 25:             }
 
What am I doing wrong??
0
 
LVL 1

Accepted Solution

by:
adam_ingeniti earned 500 total points
Comment Utility
I think you're mostly correct - you just need to use

typeof(Company.DAL.MdbClient.MdbConfig)

instead of

Type.GetType(Company.DAL.MdbClient.MdbConfig))


... GetType() is only a valid method on actual INSTANCES...  whereas typeof() works when you're referring to an actual TYPE.

Try it and see if your code works?



            typeof(DataBinder);
            (new DataBinder()).GetType();
0
 

Author Comment

by:bemara57
Comment Utility
That worked! Thanks for the help, it's exactly how I needed it to work.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now