简体   繁体   中英

dependency injection Ioc with interface segregation

I am using two database oracle and sql server. I am making system generic using dependency injection.Code is following

public interface IDatabases
{
   string GetEmployeeFullName();

}
public class OracleDB:IDatabases
{
  public string GetEmployeeFullName()
 {
   return "Name oracle";
  }
}
public class SqlServerDB : IDatabases
{
  public string GetEmployeeFullName()
  {
   return "Name sql server";
   }
}
public class RegistrationStaff 
{
  private IDatabases objDatabase;
  public RegistrationStaff(IDatabases vobjDataBase)
  {
         this.objDatabase = vobjDataBase;            
  }
}

I need another function GetEmployeeId in sql server class which will return employee id which is available in sql server database.I do not want this function implementation in oracle.How can I use interface segregation with dependency injection and implement in RegistrationStaff class .

public interface IsqlServer:IDatabases
    {
void GetEmployeeId();
}

I want only dependency injection using constructor

I think you are already on the right way. Make a new interface for the segregation, add the new method and let the SQL server class inherit from it. So after all you have to cast the database object in the Registration class to call the method. But I can't see a way without casting if you don't put the method at top level.

        public interface IDatabases
        {
            string GetEmployeeFullName();
        }

        public interface ISQLDatabase : IDatabases
        {
            int GetEmployeeId();
        }

        public class OracleDB : IDatabases
        {
            public string GetEmployeeFullName()
            {
                return "Name oracle";
            }
        }

        public class SqlServerDB : ISQLDatabase
        {
            public string GetEmployeeFullName()
            {
                return "Name sql server";
            }

            public int GetEmployeeId()
            {
                return 1;
            }
        }

        public class RegistrationStaff
        {
            private IDatabases objDatabase;

            public RegistrationStaff(IDatabases vobjDataBase)
            {
                this.objDatabase = vobjDataBase;

                if (this.objDatabase is ISQLDatabase)
                {
                    Console.WriteLine(((ISQLDatabase)this.objDatabase).GetEmployeeId());
                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM