使用 IoC 在视图模型中创建 NHibernate 存储库

发布于 2024-12-13 03:57:37 字数 2879 浏览 0 评论 0原文

我想知道如何正确构建和处理视图模型类中的 NHibernate 存储库和会话。

例如,我使用 Caliburn Micro 框架和 Castle Windsor boostraper。

首先,我创建了 NHibernate 存储库:

public interface IRepository{//I omitted not needed code for simplification}

public class NHibRepository: IRepository
{
   private ISession _session;

   public NHibRepository(ISession session)
   {
     _session=session;
   }
   // I omitted not needed code for simplification
}

其次,我使用 Fluent NHibernate 定义了一些 POCO 类和映射类。

public class User{}
public class Profile{}
public class Album{}

public class UserMap : ClassMap<User>{}
public class ProfileMap : ClassMap<Profile>{}
public class AlbumMap : ClassMap<Album>{}

现在我需要在我的视图模型中使用 NHibernate 存储库。

public interface IViewModelA{}

public class ViewModelA : ScreenViewModel, IViewModelA
{
 public NHibRepository<User> UserRepo{get;set;}
 public NHibRepository<Profile> ProfileRepo{get;set;}

}

public interface IViewModelB{}

public class ViewModelB : Screen, IViewModelB
{
 public NHibRepository<Profile> ProfileRepo{get;set;}
 public NHibRepoistory<Album> AlbumRepo{get;set;}
}

当我为某些实体类创建存储库类时,我需要将会话传递给 NHibRepository 构造函数。

UserRepo= new NHibRepository<User>(NHIBERNATE SESSION);

到目前为止,我使用了一些辅助类来创建 Nhibernate 会话和 init 存储库。

助手类在这里:

public class FluentNHibHelper
{
    private ISessionFactory _sessionFactory;

    public FluentNHibHelper(IPersistenceConfigurer db, Assembly asm)
    {
        InitializeSessionFactory(db, asm);
    }


    private void InitializeSessionFactory(IPersistenceConfigurer db, Assembly asm)
    {
        _sessionFactory = Fluently.Configure()
            .Database(db)
            .Mappings(m => m.FluentMappings.AddFromAssembly(asm))
            .ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true))
            .BuildSessionFactory();
    }

    public ISession OpenSession()
    {
        return _sessionFactory.OpenSession();
    }
}

用这个类我创建了存储库类:

private const string ConnString =
    @"Server=TestMachine\SQLEXPRESS;Database=TEST;Trusted_Connection=True;";

UserRepo = new NHibRepository<User>(
        new FluentNHibHelper(MsSqlConfiguration.MsSql2008.ConnectionString(ConnString),
            Assembly.GetExecutingAssembly())
        .OpenSession());

现在我很困惑,我不知道在视图模型中创建存储库对象的最佳方法是什么。

例如,在引导程序类中,我可以以某种方式注册存储库类吗?

public class CastleBootstrapper : Bootstrapper<IShellViewModel>
{
    private IWindsorContainer _windsorContainer;

    protected override void Configure()
    {
        _windsorContainer = new WindsorContainer();
        //register repository class here ???

    }
}

有人可以帮助我吗?非常感谢你

对不起我的英语。

I would like to how to correct build and handle with NHibernate repository and session in view models classes.

For example I use Caliburn Micro framework with Castle Windsor boostraper.

First I created NHibernate repository:

public interface IRepository{//I omitted not needed code for simplification}

public class NHibRepository: IRepository
{
   private ISession _session;

   public NHibRepository(ISession session)
   {
     _session=session;
   }
   // I omitted not needed code for simplification
}

Second I definied some POCO class and mapping class with Fluent NHibernate.

public class User{}
public class Profile{}
public class Album{}

public class UserMap : ClassMap<User>{}
public class ProfileMap : ClassMap<Profile>{}
public class AlbumMap : ClassMap<Album>{}

Now I need use NHibernate repositories in my view models.

public interface IViewModelA{}

public class ViewModelA : ScreenViewModel, IViewModelA
{
 public NHibRepository<User> UserRepo{get;set;}
 public NHibRepository<Profile> ProfileRepo{get;set;}

}

public interface IViewModelB{}

public class ViewModelB : Screen, IViewModelB
{
 public NHibRepository<Profile> ProfileRepo{get;set;}
 public NHibRepoistory<Album> AlbumRepo{get;set;}
}

When I am creating repository class for some entity class I need pass session to NHibRepository construtor.

UserRepo= new NHibRepository<User>(NHIBERNATE SESSION);

Until now I used some helper class for creating Nhibernate session and init repository.

Helper class is here:

public class FluentNHibHelper
{
    private ISessionFactory _sessionFactory;

    public FluentNHibHelper(IPersistenceConfigurer db, Assembly asm)
    {
        InitializeSessionFactory(db, asm);
    }


    private void InitializeSessionFactory(IPersistenceConfigurer db, Assembly asm)
    {
        _sessionFactory = Fluently.Configure()
            .Database(db)
            .Mappings(m => m.FluentMappings.AddFromAssembly(asm))
            .ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true))
            .BuildSessionFactory();
    }

    public ISession OpenSession()
    {
        return _sessionFactory.OpenSession();
    }
}

with this class I created repository class:

private const string ConnString =
    @"Server=TestMachine\SQLEXPRESS;Database=TEST;Trusted_Connection=True;";

UserRepo = new NHibRepository<User>(
        new FluentNHibHelper(MsSqlConfiguration.MsSql2008.ConnectionString(ConnString),
            Assembly.GetExecutingAssembly())
        .OpenSession());

Now I am confuse I don’t what is the best way for creating repository object in view models.

For example in bootstraper class can I somehow register repository class ?

public class CastleBootstrapper : Bootstrapper<IShellViewModel>
{
    private IWindsorContainer _windsorContainer;

    protected override void Configure()
    {
        _windsorContainer = new WindsorContainer();
        //register repository class here ???

    }
}

Can anybody help me? Thank you very much

Sorry for my english.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁吢 2024-12-20 03:57:37

我在 ASP.net MVC 应用程序中使用以下内容。 Castle.Windsor 负责为每个存储库创建 ISession 依赖项。

//Located in your application startup
protected IWindsorContainer CreateContainer()
{
  container = new WindsorContainer();

  container.Install(
    new PersistenceInstaller(),
    new RepositoryInstaller()
    //, other installers here
  );

  return container;
}


public class PersistenceInstaller : IWindsorInstaller
  {
      public void Install(IWindsorContainer container, IConfigurationStore store)
      {
          container.AddFacility<PersistenceFacility>();
      }
  }

public class PersistenceFacility : AbstractFacility
{
      protected override void Init()
      {
          NHibernate.Cfg.Configuration config = BuildDatabaseConfiguration();

          Kernel.Register(
              Component.For<ISessionFactory>()
                  .UsingFactoryMethod(config.BuildSessionFactory),
              Component.For<ISession>()
                  .UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession())
                  .LifeStyle.Trasient
          );
      }

      private NHibernate.Cfg.Configuration BuildDatabaseConfiguration()
      {
          return Fluently.Configure()
              .Database(SetupDatabase)
              .Mappings(m => m.HbmMappings.AddFromAssemblyOf<Entity>())
              .ExposeConfiguration(ConfigurePersistence)
              .BuildConfiguration();
      }

      protected virtual IPersistenceConfigurer SetupDatabase()
      {
          return MsSqlConfiguration.MsSql2008
              .UseOuterJoin()
              .ConnectionString(x => x.FromConnectionStringWithKey("ApplicationServices"))
              .ShowSql();
      }

      protected virtual void ConfigurePersistence(NHibernate.Cfg.Configuration config)
      {
          SchemaMetadataUpdater.QuoteTableAndColumns(config);
      }

      protected virtual bool IsDomainEntity(Type t)
      {
          return typeof(DomainBase).IsAssignableFrom(t);
      }
}



public class RepositoryInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Find().Configure(ConfigureLifeStyle()));
    }

    private ConfigureDelegate ConfigureLifeStyle()
    {
        return c => c.LifeStyle.Transient;
    }
    private BasedOnDescriptor Find()
    {
        return AllTypes.FromAssemblyContaining<NHRepository>()
                            .Where(type => type.Name.EndsWith("Repository"))
                            .WithService
                                .AllInterfaces();
    }
}

I use the following in an ASP.net MVC application. Castle.Windsor takes care of creating the ISession dependency for each repository.

//Located in your application startup
protected IWindsorContainer CreateContainer()
{
  container = new WindsorContainer();

  container.Install(
    new PersistenceInstaller(),
    new RepositoryInstaller()
    //, other installers here
  );

  return container;
}


public class PersistenceInstaller : IWindsorInstaller
  {
      public void Install(IWindsorContainer container, IConfigurationStore store)
      {
          container.AddFacility<PersistenceFacility>();
      }
  }

public class PersistenceFacility : AbstractFacility
{
      protected override void Init()
      {
          NHibernate.Cfg.Configuration config = BuildDatabaseConfiguration();

          Kernel.Register(
              Component.For<ISessionFactory>()
                  .UsingFactoryMethod(config.BuildSessionFactory),
              Component.For<ISession>()
                  .UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession())
                  .LifeStyle.Trasient
          );
      }

      private NHibernate.Cfg.Configuration BuildDatabaseConfiguration()
      {
          return Fluently.Configure()
              .Database(SetupDatabase)
              .Mappings(m => m.HbmMappings.AddFromAssemblyOf<Entity>())
              .ExposeConfiguration(ConfigurePersistence)
              .BuildConfiguration();
      }

      protected virtual IPersistenceConfigurer SetupDatabase()
      {
          return MsSqlConfiguration.MsSql2008
              .UseOuterJoin()
              .ConnectionString(x => x.FromConnectionStringWithKey("ApplicationServices"))
              .ShowSql();
      }

      protected virtual void ConfigurePersistence(NHibernate.Cfg.Configuration config)
      {
          SchemaMetadataUpdater.QuoteTableAndColumns(config);
      }

      protected virtual bool IsDomainEntity(Type t)
      {
          return typeof(DomainBase).IsAssignableFrom(t);
      }
}



public class RepositoryInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Find().Configure(ConfigureLifeStyle()));
    }

    private ConfigureDelegate ConfigureLifeStyle()
    {
        return c => c.LifeStyle.Transient;
    }
    private BasedOnDescriptor Find()
    {
        return AllTypes.FromAssemblyContaining<NHRepository>()
                            .Where(type => type.Name.EndsWith("Repository"))
                            .WithService
                                .AllInterfaces();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文