简体   繁体   English

接口隔离的依赖注入Ioc

[英]dependency injection Ioc with interface segregation

I am using two database oracle and sql server. 我正在使用两个数据库oracle和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 . 我在sql server类中需要另一个函数Ge​​tEmployeeId,该函数将返回在sql server数据库中可用的雇员id。我不希望在oracle中实现此函数。如何将接口隔离与依赖项注入一起使用并在RegistrationStaff类中实现。

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. 为隔离创建一个新接口,添加新方法,并让SQL Server类从中继承。 So after all you have to cast the database object in the Registration class to call the method. 因此,毕竟,您必须在Registration类中强制转换数据库对象以调用该方法。 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());
                }
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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