views:

58

answers:

2

Hi,

I am fairly new to .net and am creating a web app for learning purposes. I have a DAL with non static methods in it. My question is, how should i be accessing these methods in the business layer?

I'm not sure if this is a good or a bad way but currently i use this class to create instances of the DAL methods:

public DataAccess
{
    public static T GetInstance<T>(Type type)
    {
        return (T)Activator.CreateInstance(type);
    }
}

And i use the instances like this in my DLL:

public void Save(Article article)
{
    ArticleDAL art = DataAccess.GetInstance<ArticleDAL>(typeof(ArticleDAL));
    art.Save(article);
}

Any improvements or recommendations?

A: 

Yes, use a Generic constraint so no need to pass the type in at all:

public DataAccess 
{ 
    public static T GetInstance<T>() where T : new()
    { 
        return new T()
    } 
}
Mark PM
+1  A: 

There really is no reason not to just create a new instace of the DAL, the factory doesn't achieve anything here.

public void Save(Article article)
{
    ArticleDAL art = new ArticleDAL();
    art.Save(article);
}
Paul Creasey
Hi paul, thanks for the quick reply. The context is i am making a simple CMS. Would it be better in the long run in terms of maintainability for example, if i used a more generic factory such as Mark suggested, or to go with your suggestion?
geepie
The Factory Pattern is great when there is some logic involved in object creation but for simple instantiation it is pointless. For maintainability, i'd make pass the DAL into the constructor and use dependency injection.
Paul Creasey
Ok i understand, what kind of logic should belong in the factory pattern?
geepie