开发者

Registering fluent nhibernate mappings for all assemblies in an application

Starting with some code:

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"))
                    {
          开发者_如何学JAVA              m.FluentMappings.AddFromAssembly(Assembly.LoadFile(dll));
                    }
                })
                .BuildSessionFactory();

I'm very new to both nhibernate and fluent nhibernate. The bit of code above looks like it should work, but to me it looks really ugly. Is there a neater way?

One problem I have is that the code that calls the above code is in a core assembly and is unable to make reference to some of the assemblies that need mapping as their assemblies reference the core assembly. So I can't just use a few calls to AddFromAssemblyOf<T>.

Is there a cleaner way to do this?


You should be managing your SessionFactory initialization from the application itself, so your original code would work just fine.

I handle this by creating an NH config base class that does what you were originally attempting to do. I then sublcass that from within my app and do all the bootstrapping there.


You could create a custom configuration node to put in your config files.

You would have something like the following:

<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>

Then your code could be changed to something like:

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();

To create the custom config section you could see here how to do it.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜