【问题标题】:Using Multiple databases in Fluent Nhibernate, System.TypeInitializationException was unhandled在 Fluent Nhibernate 中使用多个数据库,System.TypeInitializationException 未处理
【发布时间】:2012-07-01 02:24:44
【问题描述】:

我试图实现Multiple DB connected Fluent NHibernate sample Application

我的Fluent NHibernateRepository如下:

namespace RepositoryExample.Repository.NHibernate {
    public class NHibernateRepository<T> : IRepository<T> where T : class
    {
        protected static Configuration config;
        private static readonly ISessionFactory _globalSessionFactory = new Configuration().Configure().BuildSessionFactory();

    protected static IDictionary<string, ISessionFactory> _allFactories;
    public NHibernateRepository()
    {
        IDictionary<string, string> dataBases = new Dictionary<string, string>();
        dataBases.Add("Monkey", @"Data Source=.\SQLEXPRESS;AttachDbFilename='MonkeyDB.mdf';Integrated Security=True;User Instance=True");
        dataBases.Add("Banana", @"Data Source=.\SQLEXPRESS;AttachDbFilename='Banana.mdf';Integrated Security=True;User Instance=True");
        // Error at below line (See stack trace for deatils below)
        _allFactories = new Dictionary<string, ISessionFactory>(dataBases.Count);
        foreach (var dataBase in dataBases)
        {
            config = Fluently.Configure()
                .Database(
                MsSqlConfiguration.MsSql2008.ConnectionString(dataBase.Value))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<NHibernateRepository<T>>())
                .BuildConfiguration();
            _allFactories.Add(dataBase.Key, config.BuildSessionFactory());
        }
    }
    public ISession GetSession()
    {
        var currentIdentifier = GetCurrentIdentifier();
        return _allFactories[currentIdentifier].OpenSession();
    }

    private string GetCurrentIdentifier()
    {
        if (typeof(T).ToString().Contains("Banana"))
        {
            return "Banana";
        }
        else
        {
            return "Monkey";
        }
    }
    public void Save(T value)
    {
        var sessioned = GetSession();
        using (var transaction = sessioned.BeginTransaction())
        {
            sessioned.Save(value);
            transaction.Commit();
        }
    }
    public void GenerateSchema(SanityCheck AreYouSure)
    {
        new SchemaExport(config).Create(true,true);
    } }

}

我打电话如下:

public class NHibernateIntegrationTest
    {

        static void Main(string[] args)
        {
            var repo = new NHibernateRepository<NHibernateIntegrationTest>();
            repo.GenerateSchema(SanityCheck.ThisWillDropMyDatabase);
        }
    }

错误:

_allFactories = new Dictionary<string, ISessionFactory>(dataBases.Count);

它在 NHibernateRepository 类的默认构造函数中。

StackTrace:
System.TypeInitializationException was unhandled
  Message=The type initializer for 'RepositoryExample.Repository.NHibernate.NHibernateRepository`1' threw an exception.
  Source=RepositoryExample
  TypeName=RepositoryExample.Repository.NHibernate.NHibernateRepository`1
  StackTrace:
       at RepositoryExample.Repository.NHibernate.NHibernateRepository`1..ctor() in C:\Documents and Settings\pavankumarn\My Documents\Downloads\nhibernate-repository-example\RepositoryExample\Repository\NHibernate\NHibernateRepository.cs:line 44
       at Test.NHibernateIntegrationTest.Main(String[] args) in C:\Documents and Settings\pavankumarn\My Documents\Downloads\nhibernate-repository-example\Test\NHibernateIntegrationTest.cs:line 17
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: NHibernate.Cfg.HibernateConfigException
       Message=An exception occurred during configuration of persistence layer.
       Source=NHibernate
       StackTrace:
            at NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader, Boolean fromAppSetting)
            at NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader)
            at NHibernate.Cfg.Configuration.Configure(XmlReader textReader)
            at NHibernate.Cfg.Configuration.Configure(String fileName, Boolean ignoreSessionFactoryConfig)
            at NHibernate.Cfg.Configuration.Configure(String fileName)
            at NHibernate.Cfg.Configuration.Configure()
            at RepositoryExample.Repository.NHibernate.NHibernateRepository`1..cctor() in C:\Documents and Settings\pavankumarn\My Documents\Downloads\nhibernate-repository-example\RepositoryExample\Repository\NHibernate\NHibernateRepository.cs:line 17
       InnerException: System.IO.FileNotFoundException
            Message=Could not find file 'C:\Documents and Settings\pavankumarn\My Documents\Downloads\nhibernate-repository-example\Test\bin\Debug\hibernate.cfg.xml'.
            Source=mscorlib
            FileName=C:\Documents and Settings\pavankumarn\My Documents\Downloads\nhibernate-repository-example\Test\bin\Debug\hibernate.cfg.xml
            StackTrace:
                 at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
                 at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
                 at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
                 at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
                 at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
                 at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
                 at System.Threading.CompressedStack.runTryCode(Object userData)
                 at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
                 at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
                 at System.Xml.XmlTextReaderImpl.OpenUrl()
                 at System.Xml.XmlTextReaderImpl.Read()
                 at System.Xml.XmlTextReader.Read()
                 at System.Xml.XmlCharCheckingReader.Read()
                 at System.Xml.XsdValidatingReader.Read()
                 at System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space)
                 at System.Xml.XPath.XPathDocument..ctor(XmlReader reader, XmlSpace space)
                 at System.Xml.XPath.XPathDocument..ctor(XmlReader reader)
                 at NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader, Boolean fromAppSetting)
            InnerException: 

我没有使用 hibernate.cfg.xml,因为我正在流畅地配置会话工厂。 但是内部堆栈跟踪显示找不到 hibernate.cfg.xml 文件。 请参阅下面的屏幕截图。

【问题讨论】:

标签: c# nhibernate fluent-nhibernate


【解决方案1】:

你最内在的异常中有非常明确的错误信息:

找不到文件 'C:\Documents and Settings\pavankumarn\My Documents\Downloads\nhibernate-repository-example\Test\bin\Debug\hibernate.cfg.xml'。

您的测试项目中可能有该文件。将其Build Action 设置为None 并将Copy to Output Directory 设置为Copy if newer


编辑:

其实问题不在于构造函数本身,而在于它上面的一行:

private static readonly ISessionFactory _globalSessionFactory = new Configuration().Configure().BuildSessionFactory();

在这里,您正在使用默认值创建另一个 NHibernate 配置。默认情况下,当您创建new Configuration() 时,它会尝试从app.confighibernate.cfg.xml 加载。

删除该行。我没有看到 _globaSessionFactory 在任何地方使用。

【讨论】:

  • 但我使用的是 Fluent Nhibernate。我也没有在我的存储库中的任何地方使用 hibernate.cfg.xml。
  • 你的 NHibernate 初始化是什么样的?如果您使用的代码与您所指的文章中的代码相同,那么您没有使用 FluentNHibernate,并且可能还需要有 hibernate.cfg.xml 文件。您也可以发布您的初始化代码吗?
  • 除了问题中的实体和映射之外,我发布的代码是什么。我理解的初始化代码是您在询问有关配置 ISessionFactory 的问题。如果是这样,那么它已经存在于上面的代码中的默认构造函数public NHibernateRepository()
  • 对不起,我没看到...由于某种原因,默认的 NHibernate 配置正在触发从配置文件加载。我会尝试对此进行更多研究。
  • 我们不应该在这篇文章上再做任何 cmets ......它变得太长了。您可能会创建另一个问题。这就是这个答案:您正在调用dataBases.Values.ToString(),结果将返回类似"List&lt;string&gt;" 的内容,因为dataTables.Values 是一个列表。您应该只使用 foreach 中的单个项目 - dataBase.Value
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-15
  • 1970-01-01
  • 2012-12-18
  • 2014-01-29
  • 2017-01-12
  • 2010-09-23
  • 1970-01-01
相关资源
最近更新 更多