Guidelines for build a .Net web application that c

2019-08-18 02:18发布

问题:

I'm building an application which will initially use SQLServer 2008 as the DBMS. How should I structure my application so that at a later stage I can use a different DBMS, e.g. Oracle, without changing my code i.e. via configuration only.

I suspect my core application will call code in an assembly/layer that encapsulates all the database calls required for the application to function. This layer will then call a DBMS-specific layer (based on config) to make the actual DB call? Can anyone point me to a clear example of this?

Thanks!

Added an explanation below:

My thought was that I could have multiple assemblies e.g. MyApp, MyApp.Database, MyApp.Database.SQLServer, MyApp.Database.Oracle, etc.

MyApp would make a call like:

DataSet ds = MyApp.Database.GetSomeData();

...which looks like...

public DataSet MyApp.Database.GetSomeData()
{
  return GetDataFromDBMS();
}

GetSomeData is a generic call i.e. MyApp needs "GetSomeData()" in order to do something. It doesn't care where the data is from.

Then, GetDataFromDBMS would know, via a configuration file, to call either MyApp.Database.SQLServer.GetTheData() OR MyApp.Database.Oracle.GetTheData(). These methods could do whatever is required to get/process the data from each DBMS.

回答1:

What you should look at doing is either use an ORM tool that abstracts the database for you (nHibernate), or define a set of interfaces that represent your DAL and then use an IoC implementation (Ninject, Castle, etc) to swap out the underlying implementation at will, so long as it implements the interface.

However, designing an interface that is future-proof (ie, can cope with subtle quirks of working with other databases) is not simple, so you could end up needing to make changes anyway.

I'd do one of two things, in this order:

  1. Review if you really need to swap out databases.
  2. Go down the ORM tool route as a lot of leg-work is done for you.

A good example of abstracting a database, not necessarily the DAL per-se is the Enterprise Library Data Access Application Block from Microsoft.