2012-06-27 28 views
4

我試圖實現Multiple DB connected Fluent NHibernate sample Application在Fluent Nhibernate中使用多個數據庫,System.TypeInitializationException未處理

我流利的NHibernate Repository如下:

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文件。 請參閱下面的截圖。 enter image description here

+0

請刪除導致此問題的其他問題。你不應該在Stack Overflow上做這件事。此外,您可以嘗試將問題交叉發送給nhusers小組:http://groups.google.com/group/nhusers –

+0

另外,當您達到75個聲望點時,您將有能力設置獎勵,其中將使您的問題功能和更多暴露 - http://stackoverflow.com/privileges/set-bounties –

回答

3

您在最內部異常有非常明確的錯誤消息:

找不到文件「C:\ Documents和Settings \ pavankumarn \我 的文檔\下載\ NHibernate的存儲庫,例如\測試\ BIN \調試\ hibernate.cfg.xml中」。

您可能在您的測試項目中有該文件。將其Build Action設置爲NoneCopy to Output DirectoryCopy if newer


編輯:

其實,這個問題是不是在構造函數本身,而是在它上面的一行:

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

在這裏,你在另外一臺NHibernate的配置,使用默認值。並且默認情況下,當您創建new Configuration()時,它將嘗試從app.confighibernate.cfg.xml加載。

刪除該行。我沒有看到_globaSessionFactory在任何地方使用。

+0

但我使用Fluent Nhibernate。我也沒有在我的倉庫中的任何地方使用hibernate.cfg.xml。 – viento

+0

我已經更新了與圖像的問題給你。 – viento

+0

你的NHibernate初始化是怎樣的?如果您使用的是與您所引用的文章中相同的代碼,那麼您沒有使用FluentNHibernate,並且可能還需要具有'hibernate.cfg.xml'文件。你可以發佈你的初始化代碼嗎? –

相關問題