0

我正在创建一个 asp.net mvc 网站,我需要一个建议。我有以下几层:

  • 数据库
  • 数据访问层(域对象、DAO 接口 + 基于 NHibernate 的 DAO 实现)
  • 服务层(服务接口+服务实现)
  • 表示层 (ASP.NET MVC)

实际上有几个数据库:

  • 一个具有通用数据和客户列表的数据库
  • 许多数据库 - 一个客户的每个数据库(具有相同的结构,但不需要在同一台服务器上)

DAO 和服务以这种方式“链接”:

MyMainService (contains business logic)
  MyMainDao (contains data access functions)
    MyMainSessionFactory (session factory for the main database)
      MyMainDbProvider (db provider with a connection to the main database)

或者:

MyCustomerService (contains business logic)
  MyCustomerDao (contains data access functions)
    MyCustomerSessionFactory (session factory for the customer database)
      MyCustomerDbProvider (db provider with a connection to the main database)

或混合(同时使用两个数据库):

MySuperService (contains business logic)
  MyMainDao (contains data access functions)
    MyMainSessionFactory (session factory for the main database)
      MyMainDbProvider (db provider with a connection to the main database)
  MyCustomerDao (contains data access functions)
    MyCustomerSessionFactory (session factory for the customer database)
      MyCustomerDbProvider (db provider with a connection to the main database)

我在两个提供程序中都使用了属性占位符(和 PropertyPlaceholderConfigurer)。

在这里,我们来到了我想使用这些服务的地方(在 ASP.NET MVC 控制器中):

如果我想使用 MyMainService 没有问题 - 我使用 DI 并且一切正常。

但是如果我想使用 MyCustomerService 或 MySuperService 我不认为我可以使用 DI,而是更多的“依赖拉动”。我认为我应该创建某种“服务工厂”,我将向其传递一个客户 ID,服务工厂将通过连接到相应数据库的服务返回给我。就像是:

TService GetService<TService>(int customerId)
{
  CustomerInfo info = GetCustomerInfo(customerId);
  IConfigurableApplicationContext context = (IConfigurableApplicationContext)WebApplicationContext.GetRootContext();
  PropertyPlaceholderConfigurer conf = (PropertyPlaceholderConfigurer)context.GetObject("PropertyPlaceholderConfigurer");
  conf.Properties["db.datasource"] = info.DataSource;
  conf.Properties["db.user"] = info.UserName;
  conf.Properties["db.password"] = info.Password;
  conf.Properties["db.database"] = info.DatabaseName;
  context.AddObjectFactoryPostProcessor(conf);
  context.Refresh();
  IEnumerator it = context.GetObjectsOfType(typeof(TService)).Values.GetEnumerator();
  if (it.MoveNext())
  {
    return (TService)it.Current;
  }
}

这是正确的方式还是我完全错了,我应该以其他方式这样做?

注意:会有一种情况,我想同时为不同的客户使用相同的服务,例如:

  IMyService s1 = GetService<IMyService>(1);
  IMyService s2 = GetService<IMyService>(2);
  s1.importData(s2.exportData());

任何意见,将不胜感激。

非常感谢!

4

1 回答 1

0

在“MySuperService”中,您使用两个 bean(MyMainDao 和 MyCustomerDao)。这是有效的,因为它们具有不同的类型(Java 类)。

如果您想要一个可以返回任何一个的工厂,请使用与“MySuperService”中相同的方法,但不要依赖类型,而是为两个 bean 指定不同的名称。这样,您的工厂可以按名称查找它们,您可以说:

connector = factory.lookup("name");
于 2009-06-30T12:49:37.263 回答