lundi 18 juillet 2016

dependency injection - static methods

I am trying to find the right design pattern for the below scenario.

I have a dataaccess class that can access different datasource. So I have designed to have an implementation class for each datasource(DataAccessMongo, DataAccesssql).

Based on the configuration change the data source must be switched. I believe the right way to do this is to use dependency injection and the data access class that have must accept an interface as a dependency. In the below scenario all the methods are static and I am unable to have a static method in an interface. So for now I am using a enum to check what is the data access type and call the corresponding method. If there are more data sources then definitely I should add more conditions for each data source. I would like a to arrive at a better design pattern. Please suggest what will be the best patter for this scenario. Thanks.

//Implementation class for Mongo
Public Class DataAccessMongo 
{
    public static string FindById(string itemId)
    {
    ...
    }
    public static string FindByName(string itemId)
    {
    ...
    }
    public static string FindByLastName(string itemId)
    {
    ...
    }
}

//Implementation class for Sql
Public Class DataAccessSql
{
    public static string FindById(string itemId)
    {
    ...
    }
    public static string FindByName(string itemId)
    {
    ...
    }
    public static string FindByLastName(string itemId)
    {
    ...
    }
}


Public Class DataAccess
{
    public static string FindById(string id)
    {
            string result = string.Empty;

            if (databaseType == EnumDb.Mongo)
            {
                result = DataAccessMongo.FindById(id);
            }
            else if (databaseType == EnumDb.Sql){
                result = DataAccessSql.FindById(id);
            }

            return result;
    }
    public static string FindByName(string itemId)
    {
            string result = string.Empty;

            if (databaseType == EnumDb.Mongo)
            {
                result = DataAccessMongo.FindByName(id);
            }
            else if (databaseType == EnumDb.Sql){
                result = DataAccessSql.FindByName(id);
            }

            return result;
    }
    public static string FindByLastName(string itemId)
    {
            string result = string.Empty;

            if (databaseType == EnumDb.Mongo)
            {
                result = DataAccessMongo.FindByLastName(id);
            }
            else if (databaseType == EnumDb.Sql){
                result = DataAccessSql.FindByLastName(id);
            }

            return result;
    }

}

Note: These methods serve the web API methods.

Aucun commentaire:

Enregistrer un commentaire