我正在用C#编写模块化的应用程序。我有“核心”,分为几个层,比如: DAL、BLL和表示层。所以主要问题是关于我的DAL。
在我的应用程序中,我希望有机会切换数据库。因此,在我的DAL中,我有两个文件夹: Mysql和Postgresql。
我有表:人,乐队,歌曲等(15个表)。
为了将所有这些表放在一个位置,我创建了DBData类。
public interface IDBData
{
IPersonsDAO Persons {get;}
IBandsDAO Bands {get;}
...
}
public interface IBandsDAO
{
ICollection<Band> GetBandsByPersonsInBand(int personsCount);
ICollection<Band> GetAll();
}因此,对于DAL/Postgresql中的示例,我有
public class PostgresqlDbData : IDBData
{
IConnectionFactory _connectionFactory
//tables
PostresqlPersonsDao _persons;
PostresqlBandsDao _bands;
PostgresqlDbData (IConnectionFactory connectionFactory)
{
_connectionFactory = _connectionFactory;
}
IPersonsDAO Persons get { return _persons ?? (_persons = new PostresqlPersonsDao (_connectionFactory)); }
IBandsDAO Bands get { return _bands?? (_bands = new PostresqlBandsDao (_connectionFactory)); }
...
}这样,我就可以很容易地在我的代码中获得任何dao表类,比如:
IDBData dbData = new PostgresqlDbData (connectionFactory);
ICollection<Person> persons = dbData.Persons.GetSingers();
ICollection<Band> bands = dbData.Bands.GetBandsByPersonsInBand(7);
...我为什么要这样做?
因为我使用了依赖注入,并且我不再需要在类的构造函数中输入所有我需要的表,但是我可以通过只获取IDBData的实例来获得所有的表。
///Some class that uses my IdbData
public class OrderService
{
IDBData _dbData
ShopService(IDBData dbData)
{
_dbData = dbData;
}
public void OrderAlbum(string albumName, string bandName)
{
...
IAlbum album = _dbData.Albums.GetAlbum(albumName, bandName);
..
}
public void OtherMethod(string personName)
{
...
_dbData.Persons.GetPerson(personName);
..
}
}正如您在我的OrderService中看到的,我使用的是_dbData。它被注入到构造函数中。
是的,也许它看起来像服务定位器,但我找不到其他方法来使它更好。如果我不这样做,我将需要在方法中注入每个表类。
就像我说的,我有一个模块化的应用程序。所以每个模块都是独立的,但它知道核心。当模块初始化时,它得到IDBData的实例。
例如,我有"BandsRaitingModule“模块。
这是主要的问题。
IBandsDAO只有2个方法。但是我需要像"GetBandsThatCreatedAt(int year)“这样的方法。IBandsDAO没有这个方法。在我的模块中,我想这样做
// IBandsRaitingModuleData moduleDbData;
ICollection<Band> bands = moduleDbData.Bands.GetBandsByPersonsInBand(7);
ICollection<Band> bands = moduleDbData.Bands.GetBandsThatCreatedAt(7);所以我希望能够像IDBData一样使用我的BandsRaitingModuleData,同时使用其他方法。
到达它的最佳方式是什么?
发布于 2019-06-06 20:23:34
您将不得不对更窄的接口进行一些强制转换,以获得更细粒度的函数。因此,使用较窄的方法创建一个IBandsDAO接口,并让它扩展您的IDBData接口。这将需要向下转换到更窄的接口,但不会强制您进入特定的提供程序接口,因此仍然保留您的封装。
https://stackoverflow.com/questions/56450382
复制相似问题