为应用程序中的所有程序集注册fluent nhibernate映射

为应用程序中的所有程序集注册fluent nhibernate映射,nhibernate,fluent-nhibernate,Nhibernate,Fluent Nhibernate,从一些代码开始: sessionFactory = Fluently.Configure(cfg) .Mappings(m => { List<Assembly> allAssemblies = new List<Assembly>(); string path = Assembly.GetExecutingAssembl

从一些代码开始:

sessionFactory = Fluently.Configure(cfg)
                .Mappings(m => 
                {
                    List<Assembly> allAssemblies = new List<Assembly>();
                    string path = Assembly.GetExecutingAssembly().Location;
                    foreach (string dll in Directory.GetFiles(path, "*.dll"))
                    {
                        m.FluentMappings.AddFromAssembly(Assembly.LoadFile(dll));
                    }
                })
                .BuildSessionFactory();
sessionFactory=fluent.Configure(cfg)
.Mappings(m=>
{
列出所有组件=新列表();
字符串路径=Assembly.getExecutionGassembly().Location;
foreach(Directory.GetFiles(路径“*.dll”)中的字符串dll)
{
m、 FluentMappings.AddFromAssembly(Assembly.LoadFile(dll));
}
})
.BuildSessionFactory();
我对nhibernate和流利的nhibernate都很陌生。上面的代码看起来应该可以工作,但对我来说,它看起来真的很难看。有没有更整洁的方法

我遇到的一个问题是,调用上述代码的代码位于核心程序集中,无法引用某些需要映射的程序集,因为它们的程序集引用了核心程序集。所以我不能只调用几个
AddFromAssemblyOf


有更干净的方法吗?

您可以创建一个自定义配置节点,将其放入配置文件中

您将有如下内容:

<configSections>
    <section name="fluentConfigurationsSection" type="MyCoreAssembly.FluentConfigurationsSection, MyCoreAssembly"/>
</configSections>

<fluentConfigurationsSection>
    <fluentConfigurations>
      <clear />
      <add name="Assembly1" assembly="MyAssemblyNotReferencedByCoreAssembly.Mapping.Fluent"
      <add name="Assembly2" assembly="AnotherAssemblyNotReferencedByCoreAssembly.Mapping.Fluent"
      <add name="Assembly3" assembly="OneMoreAssemblyNotReferencedByCoreAssembly.Mapping.Fluent"
    </fluentConfigurations>
</fluentConfigurationsSection>
要创建自定义配置部分,您可以查看如何进行


希望这有帮助。

您应该从应用程序本身管理SessionFactory初始化,这样您的原始代码就可以正常工作

我通过创建一个NH config基类来处理这个问题,该基类执行您最初尝试执行的操作。然后,我从我的应用程序中将其重新分类,并在那里执行所有引导

sessionFactory = Fluently.Configure(cfg)
            .Mappings(m => 
            {
                foreach(var config in MethodToGetFluentConfigSectionItems())
                {
                    //load each assembly in config file
                    m.FluentMappings.AddFromAssembly(Assembly.Load(config.Assembly); 
                }
            })
            .BuildSessionFactory();