diff --git a/CHANGELOG.md b/CHANGELOG.md
index f068f68c2..00f3ce237 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,19 +28,19 @@ Breaking Changes:
- Upgraded [Castle.Facilities.AutoTx] version to 5.3.0
- Replaced ```Castle.Services.Transaction.TransactionMode``` with ```System.Transactions.TransactionScopeOption```
- Replaced ```Castle.Services.Transaction.IsolationMode``` with ```System.Transactions.IsolationLevel```
-- Refactored ```AbstractDictionaryStackSessionStore```
+- Refactored ```Castle.Facilities.NHibernateIntegration.SessionStores.AbstractDictionaryStackSessionStore```
## 5.2.0 (2022-06-25)
Improvements:
-- Added ```AsyncLocalSessionStore```
+- Added ```Castle.Facilities.NHibernateIntegration.SessionStores.AsyncLocalSessionStore```
- Updated [Castle.Windsor] version to 5.1.2
- Updated [Castle.Services.Transaction] version to 5.2.0
- Updated [Castle.Facilities.AutoTx] version to 5.2.0
Breaking Changes:
-- Set ```AsyncLocalSessionStore``` as the default ```SessionStore```
+- Set ```Castle.Facilities.NHibernateIntegration.SessionStores.AsyncLocalSessionStore``` as the default ```SessionStore``` in ```Castle.Facilities.NHibernateIntegration.NHibernateFacility.DefaultSessionStoreType```
## 5.1.0 (2022-02-20)
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 51c09edf1..b832b5a72 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -13,13 +13,16 @@
+
+
+
@@ -28,9 +31,4 @@
-
-
-
-
-
diff --git a/build.sh b/build.sh
index 1fc804c3b..8d8d9d535 100644
--- a/build.sh
+++ b/build.sh
@@ -1,6 +1,6 @@
#!/bin/bash
# ****************************************************************************
-# Copyright 2004-2022 Castle Project - https://www.castleproject.org/
+# Copyright 2004-2024 Castle Project - https://www.castleproject.org/
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
diff --git a/buildscripts/CommonAssemblyInfo.cs b/buildscripts/CommonAssemblyInfo.cs
index 4178669c9..738c6ab4a 100644
--- a/buildscripts/CommonAssemblyInfo.cs
+++ b/buildscripts/CommonAssemblyInfo.cs
@@ -14,8 +14,6 @@
// limitations under the License.
#endregion
-using System;
-
[assembly: CLSCompliant(true)]
diff --git a/buildscripts/common.props b/buildscripts/common.props
index 59d3b8d57..8a1eaacac 100644
--- a/buildscripts/common.props
+++ b/buildscripts/common.props
@@ -8,8 +8,8 @@
true
latest
- disable
- disable
+ enable
+ enable
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/AbstractNHibernateTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/AbstractNHibernateTestCase.cs
index a3d7cf055..c4d1f64e8 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/AbstractNHibernateTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/AbstractNHibernateTestCase.cs
@@ -16,18 +16,16 @@
namespace Castle.Facilities.NHibernateIntegration.Tests
{
+ using Castle.Core.Resource;
using Castle.Facilities.AutoTx;
-
- using Core.Resource;
+ using Castle.Windsor;
+ using Castle.Windsor.Configuration.Interpreters;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NUnit.Framework;
- using Windsor;
- using Windsor.Configuration.Interpreters;
-
public abstract class AbstractNHibernateTestCase
{
protected IWindsorContainer Container;
@@ -78,7 +76,7 @@ public virtual void TearDown()
OnTearDown();
DropDatabaseSchemas();
Container.Dispose();
- Container = null;
+ Container = null!;
}
protected virtual void OnTearDown()
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/App.config b/src/Castle.Facilities.NHibernateIntegration.Tests/App.config
index 8dd4dcb18..4bfd71970 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/App.config
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/App.config
@@ -8,7 +8,7 @@
+ value="NHibernate.Dialect.MsSql2012Dialect" />
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
-
-
+
+
+
+
+
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/Blog.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/Blog.cs
index 2c0f68fce..be918b9ed 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/Blog.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/Blog.cs
@@ -27,7 +27,7 @@ public Blog()
public virtual int Id { get; set; }
- public virtual string Name { get; set; }
+ public virtual string Name { get; set; } = string.Empty;
public virtual IList Items { get; set; }
}
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogDao.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogDao.cs
index 4d18f22e5..f2ef2eee9 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogDao.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogDao.cs
@@ -19,7 +19,7 @@ namespace Castle.Facilities.NHibernateIntegration.Tests
using System.Collections;
using System.Collections.Generic;
- using MicroKernel;
+ using Castle.MicroKernel;
public class BlogDao
{
@@ -35,6 +35,7 @@ public BlogDao(IKernel kernel, ISessionManager sessionManager)
public Blog CreateBlog(string name)
{
using var session = SessionManager.OpenSession();
+
var blog = new Blog
{
Name = name,
@@ -46,22 +47,25 @@ public Blog CreateBlog(string name)
return blog;
}
- public IList ObtainBlogs()
+ public IList ObtainBlogs()
{
using var session = SessionManager.OpenSession();
- return session.CreateQuery("from Blog").List();
+
+ return session.CreateQuery("from Blog").List();
}
public void DeleteAll()
{
using var session = SessionManager.OpenSession();
+
session.Delete("from Blog");
}
- public IList ObtainBlogsStateless()
+ public IList ObtainBlogsStateless()
{
using var session = SessionManager.OpenStatelessSession();
- return session.CreateQuery("from Blog").List();
+
+ return session.CreateQuery("from Blog").List();
}
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogItem.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogItem.cs
index f02a5887e..adebc8680 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogItem.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogItem.cs
@@ -22,12 +22,12 @@ public class BlogItem
{
public virtual int Id { get; set; }
- public virtual Blog ParentBlog { get; set; }
+ public virtual Blog? ParentBlog { get; set; }
- public virtual string Title { get; set; }
+ public virtual string Title { get; set; } = string.Empty;
- public virtual string Text { get; set; }
+ public virtual string Text { get; set; } = string.Empty;
- public virtual DateTime DateTime { get; set; }
+ public virtual DateTimeOffset DateTime { get; set; }
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogItemDao.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogItemDao.cs
index 8156ac28d..89315c823 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogItemDao.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogItemDao.cs
@@ -16,7 +16,7 @@
namespace Castle.Facilities.NHibernateIntegration.Tests.Common
{
- using NHibernateIntegration.Components.Dao;
+ using Castle.Facilities.NHibernateIntegration.Components.Dao;
public class BlogItemDao : NHibernateGenericDao
{
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogRef.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogRef.cs
index 3447a4ecc..0182947fe 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogRef.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/BlogRef.cs
@@ -20,8 +20,8 @@ public class BlogRef
{
public virtual int Id { get; set; }
- public virtual Blog ParentBlog { get; set; }
+ public virtual Blog? ParentBlog { get; set; }
- public virtual string Title { get; set; }
+ public virtual string Title { get; set; } = string.Empty;
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/Order.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/Order.cs
index 61e889183..2bd840a76 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/Order.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/Order.cs
@@ -24,6 +24,6 @@ public Order()
public virtual int Id { get; set; }
- public virtual float Value { get; set; }
+ public virtual double Value { get; set; }
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/TestInterceptor.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/TestInterceptor.cs
index dda42f0fd..cdd9f30ea 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Common/TestInterceptor.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Common/TestInterceptor.cs
@@ -47,17 +47,17 @@ public void ResetState()
#region IInterceptor Members
- public override int[] FindDirty(object entity,
- object id,
- object[] currentState,
- object[] previousState,
- string[] propertyNames,
- IType[] types)
+ public override int[]? FindDirty(object entity,
+ object id,
+ object[] currentState,
+ object[] previousState,
+ string[] propertyNames,
+ IType[] types)
{
return null;
}
- public override object Instantiate(string clazz, object id)
+ public override object? Instantiate(string clazz, object id)
{
_instantiationCall = true;
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Components/NHibernateGenericDaoTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Components/NHibernateGenericDaoTestCase.cs
index 44e0e57d3..a1a655414 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Components/NHibernateGenericDaoTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Components/NHibernateGenericDaoTestCase.cs
@@ -18,13 +18,12 @@ namespace Castle.Facilities.NHibernateIntegration.Tests.Components
{
using System;
- using MicroKernel.Registration;
+ using Castle.Facilities.NHibernateIntegration.Components.Dao;
+ using Castle.MicroKernel.Registration;
using NHibernate;
using NHibernate.Criterion;
- using NHibernateIntegration.Components.Dao;
-
using NUnit.Framework;
[TestFixture]
@@ -34,9 +33,9 @@ private class NonPersistentClass
{
}
- private ISessionManager _sessionManager;
- private NHibernateGenericDao _nhGenericDao1;
- private NHibernateGenericDao _nhGenericDao2;
+ private ISessionManager _sessionManager = null!;
+ private NHibernateGenericDao _nhGenericDao1 = null!;
+ private NHibernateGenericDao _nhGenericDao2 = null!;
protected override void OnSetUp()
{
@@ -48,6 +47,7 @@ protected override void OnSetUp()
_nhGenericDao2 = new NHibernateGenericDao(_sessionManager, "sessionFactory1");
using var session = _sessionManager.OpenSession();
+
var blog1 = new Blog { Name = "myblog1" };
var blog1Item = new BlogItem
{
@@ -89,6 +89,7 @@ protected override void OnSetUp()
protected override void OnTearDown()
{
using var session = _sessionManager.OpenSession();
+
session.Delete("from BlogItem");
session.Delete("from Blog");
}
@@ -104,7 +105,9 @@ public void SetUppedCorrectly()
public void CanGetById()
{
using var session = _sessionManager.OpenSession();
- var blog = _nhGenericDao1.FindById(typeof(Blog), 1) as Blog;
+
+ var blog = (Blog) _nhGenericDao1.FindById(typeof(Blog), 1)!;
+
Assert.That(blog.Id, Is.EqualTo(1));
}
@@ -112,46 +115,61 @@ public void CanGetById()
public void CanInitializeLazyProperty()
{
using var session = _sessionManager.OpenSession();
- var b = _nhGenericDao1.FindById(typeof(Blog), 1) as Blog;
- Assert.That(NHibernateUtil.IsInitialized(b.Items), Is.False);
- _nhGenericDao1.InitializeLazyProperty(b, "Items");
- Assert.That(NHibernateUtil.IsInitialized(b.Items), Is.True);
+ var blog = (Blog) _nhGenericDao1.FindById(typeof(Blog), 1)!;
+
+ Assert.That(NHibernateUtil.IsInitialized(blog.Items), Is.False);
+
+ _nhGenericDao1.InitializeLazyProperty(blog, "Items");
+
+ Assert.That(NHibernateUtil.IsInitialized(blog.Items), Is.True);
}
[Test]
public void ThrowsExceptionOnNonExistingProperty()
{
using var session = _sessionManager.OpenSession();
- var b = _nhGenericDao1.FindById(typeof(Blog), 1) as Blog;
- Assert.Throws(() => _nhGenericDao1.InitializeLazyProperty(b, "Bla"));
+
+ var blog = (Blog) _nhGenericDao1.FindById(typeof(Blog), 1)!;
+
+ Assert.Throws(
+ () => _nhGenericDao1.InitializeLazyProperty(blog, "Bla"));
}
[Test]
public void ThrowsExceptionWhenNullInstance()
{
using var session = _sessionManager.OpenSession();
- var b = _nhGenericDao1.FindById(typeof(Blog), 1) as Blog;
- Assert.Throws(() => _nhGenericDao1.InitializeLazyProperty(null, "Items"));
- Assert.Throws(() => _nhGenericDao1.InitializeLazyProperty(b, null));
+
+ var blog = (Blog) _nhGenericDao1.FindById(typeof(Blog), 1)!;
+
+ Assert.Throws(
+ () => _nhGenericDao1.InitializeLazyProperty(null, "Items"));
+ Assert.Throws(
+ () => _nhGenericDao1.InitializeLazyProperty(blog, null));
}
[Test]
public void ThrowsExceptionWhenNullInstance2()
{
using var session = _sessionManager.OpenSession();
- Assert.Throws(() => _nhGenericDao1.InitializeLazyProperties(null));
+
+ Assert.Throws(
+ () => _nhGenericDao1.InitializeLazyProperties(null));
}
[Test]
public void CanInitializeAllLazyProperties()
{
using var session = _sessionManager.OpenSession();
- var b = _nhGenericDao1.FindById(typeof(Blog), 1) as Blog;
- Assert.That(NHibernateUtil.IsInitialized(b.Items), Is.False);
- _nhGenericDao1.InitializeLazyProperties(b);
- Assert.That(NHibernateUtil.IsInitialized(b.Items), Is.True);
+ var blog = (Blog) _nhGenericDao1.FindById(typeof(Blog), 1)!;
+
+ Assert.That(NHibernateUtil.IsInitialized(blog.Items), Is.False);
+
+ _nhGenericDao1.InitializeLazyProperties(blog);
+
+ Assert.That(NHibernateUtil.IsInitialized(blog.Items), Is.True);
}
[Test]
@@ -159,30 +177,35 @@ public void CanSaveNewItem()
{
using var session = _sessionManager.OpenSession();
using var transaction = session.BeginTransaction();
- var b = new Blog
+
+ var blog = new Blog
{
Name = "blah"
};
- _nhGenericDao1.Save(b);
- Assert.That(b.Id, Is.GreaterThan(0));
+ _nhGenericDao1.Save(blog);
+
+ Assert.That(blog.Id, Is.GreaterThan(0));
transaction.Rollback();
}
-
[Test]
public void CannotSaveNull()
{
using var session = _sessionManager.OpenSession();
- Assert.Throws(() => _nhGenericDao1.Save(new NonPersistentClass()));
+
+ Assert.Throws(
+ () => _nhGenericDao1.Save(new NonPersistentClass()));
}
[Test]
public void CanFindAll()
{
using var session = _sessionManager.OpenSession();
+
var results = _nhGenericDao1.FindAll(typeof(Blog));
+
Assert.That(results, Has.Length.EqualTo(3));
}
@@ -190,46 +213,54 @@ public void CanFindAll()
public void CanFindAllWithCriterion()
{
using var session = _sessionManager.OpenSession();
+
var results = _nhGenericDao1.FindAll(typeof(Blog),
new[] { Restrictions.Eq("Name", "myblog2") });
+
Assert.That(results, Has.Length.EqualTo(1));
- Assert.That(((Blog) results.GetValue(0)).Name, Is.EqualTo("myblog2"));
+ Assert.That(((Blog) results.GetValue(0)!).Name, Is.EqualTo("myblog2"));
}
[Test]
public void CanFindAllWithCriterionOrderBy()
{
using var session = _sessionManager.OpenSession();
+
var results = _nhGenericDao1.FindAll(typeof(BlogItem),
new[] { Restrictions.Eq("Text", "Hello") },
- new[] { Order.Desc("Title") });
+ [Order.Desc("Title")]);
+
Assert.That(results, Has.Length.EqualTo(2));
- Assert.That(((BlogItem) results.GetValue(0)).Title, Is.EqualTo("mytitle2"));
- Assert.That(((BlogItem) results.GetValue(1)).Title, Is.EqualTo("mytitle1"));
+ Assert.That(((BlogItem) results.GetValue(0)!).Title, Is.EqualTo("mytitle2"));
+ Assert.That(((BlogItem) results.GetValue(1)!).Title, Is.EqualTo("mytitle1"));
}
[Test]
public void CanFindAllWithCriterionOrderByLimits()
{
using var session = _sessionManager.OpenSession();
+
var results = _nhGenericDao1.FindAll(typeof(BlogItem),
new[] { Restrictions.Eq("Text", "Hello") },
- new[] { Order.Desc("Title") },
+ [Order.Desc("Title")],
1,
1);
+
Assert.That(results, Has.Length.EqualTo(1));
- Assert.That(((BlogItem) results.GetValue(0)).Title, Is.EqualTo("mytitle1"));
+ Assert.That(((BlogItem) results.GetValue(0)!).Title, Is.EqualTo("mytitle1"));
}
[Test]
public void CanFindAllWithCriterionOrderByLimitsOutOfRangeReturnsEmptyArray()
{
using var session = _sessionManager.OpenSession();
+
var results = _nhGenericDao1.FindAll(typeof(BlogItem),
new[] { Restrictions.Eq("Text", "Hello") },
- new[] { Order.Desc("Title") },
+ [Order.Desc("Title")],
2,
3);
+
Assert.That(results, Has.Length.EqualTo(0));
}
@@ -237,9 +268,11 @@ public void CanFindAllWithCriterionOrderByLimitsOutOfRangeReturnsEmptyArray()
public void CanFindAllWithLimits()
{
using var session = _sessionManager.OpenSession();
+
var results = _nhGenericDao1.FindAll(typeof(BlogItem),
1,
2);
+
Assert.That(results, Has.Length.EqualTo(2));
}
@@ -247,9 +280,11 @@ public void CanFindAllWithLimits()
public void CanFindAllWithLimitsOutOfRangeReturnsEmptyArray()
{
using var session = _sessionManager.OpenSession();
+
var results = _nhGenericDao1.FindAll(typeof(BlogItem),
3,
4);
+
Assert.That(results, Has.Length.EqualTo(0));
}
@@ -257,19 +292,23 @@ public void CanFindAllWithLimitsOutOfRangeReturnsEmptyArray()
public void CanFindAllWithCriterionLimit()
{
using var session = _sessionManager.OpenSession();
+
var results = _nhGenericDao1.FindAll(typeof(BlogItem),
new[] { Restrictions.Eq("Text", "Hello") },
0,
1);
+
Assert.That(results, Has.Length.EqualTo(1));
- Assert.That(((BlogItem) results.GetValue(0)).Title, Is.EqualTo("mytitle1"));
+ Assert.That(((BlogItem) results.GetValue(0)!).Title, Is.EqualTo("mytitle1"));
}
[Test]
public void FindAllWithCustomQuery()
{
using var session = _sessionManager.OpenSession();
+
var results = _nhGenericDao1.FindAllWithCustomQuery("from BlogItem b where b.Text='Hello'");
+
Assert.That(results, Has.Length.EqualTo(2));
}
@@ -277,7 +316,9 @@ public void FindAllWithCustomQuery()
public void FindAllWithCustomQueryLimits()
{
using var session = _sessionManager.OpenSession();
+
var results = _nhGenericDao1.FindAllWithCustomQuery("from BlogItem b where b.Text='Hello'", 1, 1);
+
Assert.That(results, Has.Length.EqualTo(1));
}
@@ -295,6 +336,7 @@ public void DeleteAllWithType()
using (var session = _sessionManager.OpenSession())
{
var results = _nhGenericDao1.FindAll(typeof(Blog));
+
Assert.That(results, Has.Length.EqualTo(0));
}
}
@@ -305,6 +347,7 @@ public void Delete()
using (var session = _sessionManager.OpenSession())
{
var results = _nhGenericDao1.FindAll(typeof(Blog));
+
Assert.That(results, Has.Length.EqualTo(3));
}
@@ -321,6 +364,7 @@ public void Delete()
using (var session = _sessionManager.OpenSession())
{
var results = _nhGenericDao1.FindAll(typeof(Blog));
+
Assert.That(results, Has.Length.EqualTo(2));
}
}
@@ -329,16 +373,20 @@ public void Delete()
public void CreateSavesObjectInTheDatabase()
{
using var session = _sessionManager.OpenSession();
- var b = new Blog { Name = "myblog4" };
- var id = _nhGenericDao1.Create(b);
- Assert.That(id, Is.GreaterThan(0));
+
+ var blog = new Blog { Name = "myblog4" };
+ var blogId = _nhGenericDao1.Create(blog);
+
+ Assert.That(blogId, Is.GreaterThan(0));
}
[Test]
public void GetByNamedQuery()
{
using var session = _sessionManager.OpenSession();
+
var results = _nhGenericDao1.FindAllWithNamedQuery("getAllBlogs");
+
Assert.That(results, Has.Length.EqualTo(3));
}
@@ -346,21 +394,27 @@ public void GetByNamedQuery()
public void GetByNamedQueryThrowsExceptionWhenNullParameter()
{
using var session = _sessionManager.OpenSession();
- Assert.Throws(() => _nhGenericDao1.FindAllWithNamedQuery(null));
+
+ Assert.Throws(
+ () => _nhGenericDao1.FindAllWithNamedQuery(null));
}
[Test]
public void GetByNamedQueryThrowsExceptionWhenNonExistingQuery()
{
using var session = _sessionManager.OpenSession();
- Assert.Throws(() => _nhGenericDao1.FindAllWithNamedQuery("getMyBlogs"));
+
+ Assert.Throws(
+ () => _nhGenericDao1.FindAllWithNamedQuery("getMyBlogs"));
}
[Test]
public void GetByNamedQueryWithLimits()
{
using var session = _sessionManager.OpenSession();
+
var results = _nhGenericDao1.FindAllWithNamedQuery("getAllBlogs", 1, 2);
+
Assert.That(results, Has.Length.EqualTo(2));
}
@@ -369,7 +423,9 @@ public void GetByNamedQueryWithLimits()
public void CanFindAllStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
var results = _nhGenericDao1.FindAllStateless(typeof(Blog));
+
Assert.That(results, Has.Length.EqualTo(3));
}
@@ -377,45 +433,53 @@ public void CanFindAllStateless()
public void CanFindAllWithCriterionStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
var results = _nhGenericDao1.FindAllStateless(
typeof(Blog),
new[] { Restrictions.Eq("Name", "myblog2") });
+
Assert.That(results, Has.Length.EqualTo(1));
- Assert.That(((Blog) results.GetValue(0)).Name, Is.EqualTo("myblog2"));
+ Assert.That(((Blog) results.GetValue(0)!).Name, Is.EqualTo("myblog2"));
}
[Test]
public void CanFindAllWithCriterionOrderByStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
var results = _nhGenericDao1.FindAllStateless(
typeof(BlogItem),
new[] { Restrictions.Eq("Text", "Hello") },
- new[] { Order.Desc("Title") });
+ [Order.Desc("Title")]);
+
Assert.That(results, Has.Length.EqualTo(2));
- Assert.That(((BlogItem) results.GetValue(0)).Title, Is.EqualTo("mytitle2"));
- Assert.That(((BlogItem) results.GetValue(1)).Title, Is.EqualTo("mytitle1"));
+ Assert.That(((BlogItem) results.GetValue(0)!).Title, Is.EqualTo("mytitle2"));
+ Assert.That(((BlogItem) results.GetValue(1)!).Title, Is.EqualTo("mytitle1"));
}
[Test]
public void CanFindAllWithCriterionOrderByLimitsStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
var results = _nhGenericDao1.FindAll(typeof(BlogItem),
new[] { Restrictions.Eq("Text", "Hello") },
- new[] { Order.Desc("Title") }, 1, 1);
+ [Order.Desc("Title")], 1, 1);
+
Assert.That(results, Has.Length.EqualTo(1));
- Assert.That(((BlogItem) results.GetValue(0)).Title, Is.EqualTo("mytitle1"));
+ Assert.That(((BlogItem) results.GetValue(0)!).Title, Is.EqualTo("mytitle1"));
}
[Test]
public void CanFindAllWithCriterionOrderByLimitsOutOfRangeReturnsEmptyArrayStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
var results = _nhGenericDao1.FindAllStateless(
typeof(BlogItem),
new[] { Restrictions.Eq("Text", "Hello") },
- new[] { Order.Desc("Title") }, 2, 3);
+ [Order.Desc("Title")], 2, 3);
+
Assert.That(results, Has.Length.EqualTo(0));
}
@@ -423,9 +487,11 @@ public void CanFindAllWithCriterionOrderByLimitsOutOfRangeReturnsEmptyArrayState
public void CanFindAllWithLimitsStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
var results = _nhGenericDao1.FindAllStateless(typeof(BlogItem),
1,
2);
+
Assert.That(results, Has.Length.EqualTo(2));
}
@@ -433,9 +499,11 @@ public void CanFindAllWithLimitsStateless()
public void CanFindAllWithLimitsOutOfRangeReturnsEmptyArrayStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
var results = _nhGenericDao1.FindAllStateless(typeof(BlogItem),
3,
4);
+
Assert.That(results, Has.Length.EqualTo(0));
}
@@ -443,19 +511,23 @@ public void CanFindAllWithLimitsOutOfRangeReturnsEmptyArrayStateless()
public void CanFindAllWithCriterionLimitStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
var results = _nhGenericDao1.FindAllStateless(typeof(BlogItem),
new[] { Restrictions.Eq("Text", "Hello") },
0,
1);
+
Assert.That(results, Has.Length.EqualTo(1));
- Assert.That(((BlogItem) results.GetValue(0)).Title, Is.EqualTo("mytitle1"));
+ Assert.That(((BlogItem) results.GetValue(0)!).Title, Is.EqualTo("mytitle1"));
}
[Test]
public void FindAllWithCustomQueryStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
var results = _nhGenericDao1.FindAllWithCustomQueryStateless("from BlogItem b where b.Text='Hello'");
+
Assert.That(results, Has.Length.EqualTo(2));
}
@@ -463,7 +535,9 @@ public void FindAllWithCustomQueryStateless()
public void FindAllWithCustomQueryLimitsStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
var results = _nhGenericDao1.FindAllWithCustomQueryStateless("from BlogItem b where b.Text='Hello'", 1, 1);
+
Assert.That(results, Has.Length.EqualTo(1));
}
@@ -471,7 +545,9 @@ public void FindAllWithCustomQueryLimitsStateless()
public void GetByNamedQueryStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
var results = _nhGenericDao1.FindAllWithNamedQueryStateless("getAllBlogs");
+
Assert.That(results, Has.Length.EqualTo(3));
}
@@ -479,6 +555,7 @@ public void GetByNamedQueryStateless()
public void GetByNamedQueryThrowsExceptionWhenNullParameterStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
Assert.Throws(() => _nhGenericDao1.FindAllWithNamedQueryStateless(null));
}
@@ -486,6 +563,7 @@ public void GetByNamedQueryThrowsExceptionWhenNullParameterStateless()
public void GetByNamedQueryThrowsExceptionWhenNonExistingQueryStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
Assert.Throws(() => _nhGenericDao1.FindAllWithNamedQueryStateless("getMyBlogs"));
}
@@ -493,7 +571,9 @@ public void GetByNamedQueryThrowsExceptionWhenNonExistingQueryStateless()
public void GetByNamedQueryWithLimitsStateless()
{
using var session = _sessionManager.OpenStatelessSession();
+
var results = _nhGenericDao1.FindAllWithNamedQueryStateless("getAllBlogs", 1, 2);
+
Assert.That(results, Has.Length.EqualTo(2));
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Components/ReflectionUtilityTests.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Components/ReflectionUtilityTests.cs
index 3a5d0d626..ecab367e0 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Components/ReflectionUtilityTests.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Components/ReflectionUtilityTests.cs
@@ -19,9 +19,9 @@ namespace Castle.Facilities.NHibernateIntegration.Tests.Components
using System;
using System.Collections.Generic;
- using NUnit.Framework;
+ using Castle.Facilities.NHibernateIntegration.Util;
- using Util;
+ using NUnit.Framework;
[TestFixture]
public class ReflectionUtilityTests
@@ -41,6 +41,7 @@ public void CanGetPropertiesAsDictionary()
new() { }
}
};
+
var dictionary = ReflectionUtility.GetPropertiesDictionary(blog);
Assert.That(dictionary.ContainsKey("Name"));
Assert.That(dictionary.ContainsKey("Id"));
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/ConfigurationBuilderRegression.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/ConfigurationBuilderRegression.xml
index 2136455f0..793f30c0c 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/ConfigurationBuilderRegression.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/ConfigurationBuilderRegression.xml
@@ -9,7 +9,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/CustomConfigurationBuilder.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/CustomConfigurationBuilder.xml
index d3605d425..7d7c4cb7d 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/CustomConfigurationBuilder.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/CustomConfigurationBuilder.xml
@@ -10,7 +10,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/DaoTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/DaoTestCase.cs
index 1cc4513cb..aea42a74b 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/DaoTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/DaoTestCase.cs
@@ -16,7 +16,7 @@
namespace Castle.Facilities.NHibernateIntegration.Tests.Common
{
- using MicroKernel.Registration;
+ using Castle.MicroKernel.Registration;
using NUnit.Framework;
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/DefaultConfiguration.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/DefaultConfiguration.xml
index e057b21f8..41fb4f066 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/DefaultConfiguration.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/DefaultConfiguration.xml
@@ -16,7 +16,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/AsyncLocalSessionStoreConfiguration.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/AsyncLocalSessionStoreConfiguration.xml
index af063d460..26d030b86 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/AsyncLocalSessionStoreConfiguration.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/AsyncLocalSessionStoreConfiguration.xml
@@ -9,15 +9,15 @@
+ configurationBuilder="Castle.Facilities.NHibernateIntegration.Tests.TestConfigurationBuilder, Castle.Facilities.NHibernateIntegration.Tests"
+ sessionStore="Castle.Facilities.NHibernateIntegration.SessionStores.AsyncLocalSessionStore, Castle.Facilities.NHibernateIntegration">
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/AsyncLocalSessionStoreTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/AsyncLocalSessionStoreTestCase.cs
index 4fa23d157..7eb5121c4 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/AsyncLocalSessionStoreTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/AsyncLocalSessionStoreTestCase.cs
@@ -55,7 +55,7 @@ public void FindCompatibleSession()
var store = Container.Resolve();
var factory = Container.Resolve();
- ISession session1 = store.FindCompatibleSession(Constants.DefaultAlias);
+ ISession? session1 = store.FindCompatibleSession(Constants.DefaultAlias);
Assert.That(session1, Is.Null);
session1 = factory.OpenSession();
@@ -63,7 +63,7 @@ public void FindCompatibleSession()
store.Store(Constants.DefaultAlias, sessionDelegate1);
Assert.That(sessionDelegate1.SessionStoreCookie, Is.Not.Null);
- ISession session2 = store.FindCompatibleSession("something in the way she moves");
+ ISession? session2 = store.FindCompatibleSession("something in the way she moves");
Assert.That(session2, Is.Null);
session2 = store.FindCompatibleSession(Constants.DefaultAlias);
@@ -89,7 +89,7 @@ public void FindCompatibleSessionWithTwoThreads()
var session1 = factory.OpenSession();
var sessionDelegate1 = new SessionDelegate(session1, store, true);
store.Store(Constants.DefaultAlias, sessionDelegate1);
- ISession session2 = store.FindCompatibleSession(Constants.DefaultAlias);
+ ISession? session2 = store.FindCompatibleSession(Constants.DefaultAlias);
Assert.That(session2, Is.Not.Null);
Assert.That(session2, Is.SameAs(sessionDelegate1));
@@ -107,10 +107,10 @@ private void FindCompatibleSessionOnOtherThread()
{
var store = Container.Resolve();
- ISession session1 = store.FindCompatibleSession("something in the way she moves");
+ ISession? session1 = store.FindCompatibleSession("something in the way she moves");
Assert.That(session1, Is.Null);
- ISession session2 = store.FindCompatibleSession(Constants.DefaultAlias);
+ ISession? session2 = store.FindCompatibleSession(Constants.DefaultAlias);
Assert.That(session2, Is.Not.Null);
_event.Set();
@@ -130,7 +130,7 @@ public void FindCompatibleStatelessSession()
var store = Container.Resolve();
var factory = Container.Resolve();
- IStatelessSession session1 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
+ IStatelessSession? session1 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
Assert.That(session1, Is.Null);
session1 = factory.OpenStatelessSession();
@@ -138,7 +138,7 @@ public void FindCompatibleStatelessSession()
store.Store(Constants.DefaultAlias, sessionDelegate1);
Assert.That(sessionDelegate1.SessionStoreCookie, Is.Not.Null);
- IStatelessSession session2 = store.FindCompatibleStatelessSession("something in the way she moves");
+ IStatelessSession? session2 = store.FindCompatibleStatelessSession("something in the way she moves");
Assert.That(session2, Is.Null);
session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
@@ -165,7 +165,7 @@ public void FindCompatibleStatelessSessionWithTwoThreads()
var sessionDelegate1 = new StatelessSessionDelegate(session1, store, true);
store.Store(Constants.DefaultAlias, sessionDelegate1);
- IStatelessSession session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
+ IStatelessSession? session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
Assert.That(session2, Is.Not.Null);
Assert.That(session2, Is.SameAs(sessionDelegate1));
@@ -183,10 +183,10 @@ private void FindCompatibleStatelessSessionOnOtherThread()
{
var store = Container.Resolve();
- IStatelessSession session1 = store.FindCompatibleStatelessSession("something in the way she moves");
+ IStatelessSession? session1 = store.FindCompatibleStatelessSession("something in the way she moves");
Assert.That(session1, Is.Null);
- IStatelessSession session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
+ IStatelessSession? session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
Assert.That(session2, Is.Not.Null);
_event.Set();
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/CallContextSessionStoreConfiguration.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/CallContextSessionStoreConfiguration.xml
index e0711596f..c92c29efb 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/CallContextSessionStoreConfiguration.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/CallContextSessionStoreConfiguration.xml
@@ -9,15 +9,15 @@
+ configurationBuilder="Castle.Facilities.NHibernateIntegration.Tests.TestConfigurationBuilder, Castle.Facilities.NHibernateIntegration.Tests"
+ sessionStore="Castle.Facilities.NHibernateIntegration.SessionStores.CallContextSessionStore, Castle.Facilities.NHibernateIntegration">
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/CallContextSessionStoreTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/CallContextSessionStoreTestCase.cs
index e1c57dd77..3532f5b1c 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/CallContextSessionStoreTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/CallContextSessionStoreTestCase.cs
@@ -14,9 +14,9 @@
// limitations under the License.
#endregion
+#if NETFRAMEWORK
namespace Castle.Facilities.NHibernateIntegration.Tests.Internals
{
-#if NETFRAMEWORK
using System;
using System.Threading;
@@ -54,7 +54,7 @@ public void FindCompatibleSession()
var store = Container.Resolve();
var factory = Container.Resolve();
- ISession session1 = store.FindCompatibleSession(Constants.DefaultAlias);
+ ISession? session1 = store.FindCompatibleSession(Constants.DefaultAlias);
Assert.That(session1, Is.Null);
session1 = factory.OpenSession();
@@ -62,7 +62,7 @@ public void FindCompatibleSession()
store.Store(Constants.DefaultAlias, sessionDelegate1);
Assert.That(sessionDelegate1.SessionStoreCookie, Is.Not.Null);
- ISession session2 = store.FindCompatibleSession("something in the way she moves");
+ ISession? session2 = store.FindCompatibleSession("something in the way she moves");
Assert.That(session2, Is.Null);
session2 = store.FindCompatibleSession(Constants.DefaultAlias);
@@ -88,7 +88,8 @@ public void FindCompatibleSessionWithTwoThreads()
var session1 = factory.OpenSession();
var sessionDelegate1 = new SessionDelegate(session1, store, true);
store.Store(Constants.DefaultAlias, sessionDelegate1);
- ISession session2 = store.FindCompatibleSession(Constants.DefaultAlias);
+
+ ISession? session2 = store.FindCompatibleSession(Constants.DefaultAlias);
Assert.That(session2, Is.Not.Null);
Assert.That(session2, Is.SameAs(sessionDelegate1));
@@ -106,10 +107,10 @@ private void FindCompatibleSessionOnOtherThread()
{
var store = Container.Resolve();
- ISession session1 = store.FindCompatibleSession("something in the way she moves");
+ ISession? session1 = store.FindCompatibleSession("something in the way she moves");
Assert.That(session1, Is.Null);
- ISession session2 = store.FindCompatibleSession(Constants.DefaultAlias);
+ ISession? session2 = store.FindCompatibleSession(Constants.DefaultAlias);
Assert.That(session2, Is.Null);
_event.Set();
@@ -129,7 +130,7 @@ public void FindCompatibleStatelessSession()
var store = Container.Resolve();
var factory = Container.Resolve();
- IStatelessSession session1 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
+ IStatelessSession? session1 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
Assert.That(session1, Is.Null);
session1 = factory.OpenStatelessSession();
@@ -137,7 +138,7 @@ public void FindCompatibleStatelessSession()
store.Store(Constants.DefaultAlias, sessionDelegate1);
Assert.That(sessionDelegate1.SessionStoreCookie, Is.Not.Null);
- IStatelessSession session2 = store.FindCompatibleStatelessSession("something in the way she moves");
+ IStatelessSession? session2 = store.FindCompatibleStatelessSession("something in the way she moves");
Assert.That(session2, Is.Null);
session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
@@ -164,7 +165,7 @@ public void FindCompatibleStatelessSessionWithTwoThreads()
var sessionDelegate1 = new StatelessSessionDelegate(session1, store, true);
store.Store(Constants.DefaultAlias, sessionDelegate1);
- IStatelessSession session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
+ IStatelessSession? session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
Assert.That(session2, Is.Not.Null);
Assert.That(session2, Is.SameAs(sessionDelegate1));
@@ -182,14 +183,14 @@ private void FindCompatibleStatelessSessionOnOtherThread()
{
var store = Container.Resolve();
- IStatelessSession session1 = store.FindCompatibleStatelessSession("something in the way she moves");
+ IStatelessSession? session1 = store.FindCompatibleStatelessSession("something in the way she moves");
Assert.That(session1, Is.Null);
- IStatelessSession session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
+ IStatelessSession? session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
Assert.That(session2, Is.Null);
_event.Set();
}
}
-#endif
}
+#endif
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/LogicalCallContextSessionStoreConfiguration.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/LogicalCallContextSessionStoreConfiguration.xml
index 567a95772..137da9e7e 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/LogicalCallContextSessionStoreConfiguration.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/LogicalCallContextSessionStoreConfiguration.xml
@@ -9,15 +9,15 @@
+ configurationBuilder="Castle.Facilities.NHibernateIntegration.Tests.TestConfigurationBuilder, Castle.Facilities.NHibernateIntegration.Tests"
+ sessionStore="Castle.Facilities.NHibernateIntegration.SessionStores.LogicalCallContextSessionStore, Castle.Facilities.NHibernateIntegration">
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/LogicalCallContextSessionStoreTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/LogicalCallContextSessionStoreTestCase.cs
index 797f85d1f..5f11d1d92 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/LogicalCallContextSessionStoreTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/LogicalCallContextSessionStoreTestCase.cs
@@ -14,9 +14,9 @@
// limitations under the License.
#endregion
+#if NETFRAMEWORK
namespace Castle.Facilities.NHibernateIntegration.Tests.Internals
{
-#if NETFRAMEWORK
using System;
using System.Threading;
@@ -56,7 +56,7 @@ public void FindCompatibleSession()
var store = Container.Resolve();
var factory = Container.Resolve();
- ISession session1 = store.FindCompatibleSession(Constants.DefaultAlias);
+ ISession? session1 = store.FindCompatibleSession(Constants.DefaultAlias);
Assert.That(session1, Is.Null);
session1 = factory.OpenSession();
@@ -64,7 +64,7 @@ public void FindCompatibleSession()
store.Store(Constants.DefaultAlias, sessionDelegate1);
Assert.That(sessionDelegate1.SessionStoreCookie, Is.Not.Null);
- ISession session2 = store.FindCompatibleSession("something in the way she moves");
+ ISession? session2 = store.FindCompatibleSession("something in the way she moves");
Assert.That(session2, Is.Null);
session2 = store.FindCompatibleSession(Constants.DefaultAlias);
@@ -91,7 +91,7 @@ public void FindCompatibleSessionWithTwoThreads()
var sessionDelegate1 = new SessionDelegate(session1, store, true);
store.Store(Constants.DefaultAlias, sessionDelegate1);
- ISession session2 = store.FindCompatibleSession(Constants.DefaultAlias);
+ ISession? session2 = store.FindCompatibleSession(Constants.DefaultAlias);
Assert.That(session2, Is.Not.Null);
Assert.That(session2, Is.SameAs(sessionDelegate1));
@@ -109,10 +109,10 @@ private void FindCompatibleSessionOnOtherThread()
{
var store = Container.Resolve();
- ISession session1 = store.FindCompatibleSession("something in the way she moves");
+ ISession? session1 = store.FindCompatibleSession("something in the way she moves");
Assert.That(session1, Is.Null);
- ISession session2 = store.FindCompatibleSession(Constants.DefaultAlias);
+ ISession? session2 = store.FindCompatibleSession(Constants.DefaultAlias);
Assert.That(session2, Is.Not.Null);
_event.Set();
@@ -132,7 +132,7 @@ public void FindCompatibleStatelessSession()
var store = Container.Resolve();
var factory = Container.Resolve();
- IStatelessSession session1 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
+ IStatelessSession? session1 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
Assert.That(session1, Is.Null);
session1 = factory.OpenStatelessSession();
@@ -140,7 +140,7 @@ public void FindCompatibleStatelessSession()
store.Store(Constants.DefaultAlias, sessionDelegate1);
Assert.That(sessionDelegate1.SessionStoreCookie, Is.Not.Null);
- IStatelessSession session2 = store.FindCompatibleStatelessSession("something in the way she moves");
+ IStatelessSession? session2 = store.FindCompatibleStatelessSession("something in the way she moves");
Assert.That(session2, Is.Null);
session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
@@ -166,7 +166,7 @@ public void FindCompatibleStatelessSessionWithTwoThreads()
var session1 = factory.OpenStatelessSession();
var sessionDelegate1 = new StatelessSessionDelegate(session1, store, true);
store.Store(Constants.DefaultAlias, sessionDelegate1);
- IStatelessSession session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
+ IStatelessSession? session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
Assert.That(session2, Is.Not.Null);
Assert.That(session2, Is.SameAs(sessionDelegate1));
@@ -185,14 +185,14 @@ private void FindCompatibleStatelessSessionOnOtherThread()
{
var store = Container.Resolve();
- IStatelessSession session1 = store.FindCompatibleStatelessSession("something in the way she moves");
+ IStatelessSession? session1 = store.FindCompatibleStatelessSession("something in the way she moves");
Assert.That(session1, Is.Null);
- IStatelessSession session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
+ IStatelessSession? session2 = store.FindCompatibleStatelessSession(Constants.DefaultAlias);
Assert.That(session2, Is.Not.Null);
_event.Set();
}
}
-#endif
}
+#endif
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/SessionManagerTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/SessionManagerTestCase.cs
index 2c38b81d2..21667304e 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/SessionManagerTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/SessionManagerTestCase.cs
@@ -70,12 +70,13 @@ public void NewTransactionAfterUsingSession()
var session1 = manager.OpenSession();
- var transactionManager = Container.Resolve();
- var transaction =
- transactionManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
- System.Transactions.IsolationLevel.Serializable);
+ var txManager = Container.Resolve();
- transaction.Begin();
+ var tx = txManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
+ System.Transactions.IsolationLevel.Serializable);
+ Assert.That(tx, Is.Not.Null);
+
+ tx.Begin();
// Nested
using (var session2 = manager.OpenSession())
@@ -83,30 +84,29 @@ public void NewTransactionAfterUsingSession()
Assert.That(session2, Is.Not.Null);
Assert.That(session1, Is.Not.Null);
- var transaction1 = session1.GetCurrentTransaction();
- Assert.That(transaction1, Is.Not.Null,
- "After requesting compatible session, first session is enlisted in transaction too.");
- Assert.That(transaction1.IsActive, Is.True,
- "After requesting compatible session, first session is enlisted in transaction too.");
+ var tx1 = session1.GetCurrentTransaction();
+ Assert.That(tx1, Is.Not.Null,
+ "After requesting compatible session, first session is enlisted in transaction too.");
+ Assert.That(tx1.IsActive, Is.True,
+ "After requesting compatible session, first session is enlisted in transaction too.");
using (var session3 = manager.OpenSession())
{
Assert.That(session3, Is.Not.Null);
- var transaction3 = session3.GetCurrentTransaction();
- Assert.That(transaction3, Is.Not.Null);
- Assert.That(transaction3.IsActive, Is.True);
+ var tx3 = session3.GetCurrentTransaction();
+ Assert.That(tx3, Is.Not.Null);
+ Assert.That(tx3.IsActive, Is.True);
}
var sessionDelegate1 = (SessionDelegate) session1;
var sessionDelegate2 = (SessionDelegate) session2;
-
Assert.That(sessionDelegate2.InnerSession, Is.SameAs(sessionDelegate1.InnerSession));
}
- transaction.Commit();
+ tx.Commit();
- Assert.That(transaction.Status == TransactionStatus.Committed, Is.True);
+ Assert.That(tx.Status == TransactionStatus.Committed, Is.True);
Assert.That(session1.IsConnected, Is.True);
session1.Dispose();
@@ -125,12 +125,13 @@ public void NewTransactionAfterUsingStatelessSession()
var session1 = manager.OpenStatelessSession();
- var transactionManager = Container.Resolve();
- var transaction =
- transactionManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
- System.Transactions.IsolationLevel.Serializable);
+ var txManager = Container.Resolve();
- transaction.Begin();
+ var tx = txManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
+ System.Transactions.IsolationLevel.Serializable);
+ Assert.That(tx, Is.Not.Null);
+
+ tx.Begin();
// Nested
using (var session2 = manager.OpenStatelessSession())
@@ -138,19 +139,19 @@ public void NewTransactionAfterUsingStatelessSession()
Assert.That(session2, Is.Not.Null);
Assert.That(session1, Is.Not.Null);
- var transaction1 = session1.GetCurrentTransaction();
- Assert.That(transaction1, Is.Not.Null,
- "After requesting compatible session, first session is enlisted in transaction too.");
- Assert.That(transaction1.IsActive, Is.True,
- "After requesting compatible session, first session is enlisted in transaction too.");
+ var tx1 = session1.GetCurrentTransaction();
+ Assert.That(tx1, Is.Not.Null,
+ "After requesting compatible session, first session is enlisted in transaction too.");
+ Assert.That(tx1.IsActive, Is.True,
+ "After requesting compatible session, first session is enlisted in transaction too.");
using (var session3 = manager.OpenSession())
{
Assert.That(session3, Is.Not.Null);
- var transaction3 = session3.GetCurrentTransaction();
- Assert.That(transaction3, Is.Not.Null);
- Assert.That(transaction3.IsActive, Is.True);
+ var tx3 = session3.GetCurrentTransaction();
+ Assert.That(tx3, Is.Not.Null);
+ Assert.That(tx3.IsActive, Is.True);
}
var sessionDelegate1 = (StatelessSessionDelegate) session1;
@@ -158,9 +159,9 @@ public void NewTransactionAfterUsingStatelessSession()
Assert.That(sessionDelegate2.InnerSession, Is.SameAs(sessionDelegate1.InnerSession));
}
- transaction.Commit();
+ tx.Commit();
- Assert.That(transaction.Status == TransactionStatus.Committed, Is.True);
+ Assert.That(tx.Status == TransactionStatus.Committed, Is.True);
Assert.That(session1.IsConnected, Is.True);
session1.Dispose();
@@ -177,21 +178,23 @@ public void NewTransactionBeforeUsingSession()
{
var manager = Container.Resolve();
- var transactionManager = Container.Resolve();
- var transaction =
- transactionManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
- System.Transactions.IsolationLevel.Serializable);
+ var txManager = Container.Resolve();
+
+ var tx = txManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
+ System.Transactions.IsolationLevel.Serializable);
+ Assert.That(tx, Is.Not.Null);
- transaction.Begin();
+ tx.Begin();
var session = manager.OpenSession();
+
Assert.That(session, Is.Not.Null);
Assert.That(session.GetCurrentTransaction(), Is.Not.Null);
Assert.That(session.IsConnected, Is.True);
- transaction.Commit();
+ tx.Commit();
- Assert.That(transaction.Status == TransactionStatus.Committed, Is.True);
+ Assert.That(tx.Status == TransactionStatus.Committed, Is.True);
session.Dispose();
@@ -206,26 +209,29 @@ public void NewTransactionBeforeUsingSessionWithTwoDatabases()
{
var manager = Container.Resolve();
- var transactionManager = Container.Resolve();
- var transaction =
- transactionManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
- System.Transactions.IsolationLevel.Serializable);
+ var txManager = Container.Resolve();
+ var tx = txManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
+ System.Transactions.IsolationLevel.Serializable);
+
+ Assert.That(tx, Is.Not.Null);
- transaction.Begin();
+ tx.Begin();
var session1 = manager.OpenSession();
+
Assert.That(session1, Is.Not.Null);
Assert.That(session1.GetCurrentTransaction(), Is.Not.Null);
Assert.That(session1.IsConnected, Is.True);
var session2 = manager.OpenSession("db2");
+
Assert.That(session2, Is.Not.Null);
Assert.That(session2.GetCurrentTransaction(), Is.Not.Null);
Assert.That(session2.IsConnected, Is.True);
- transaction.Commit();
+ tx.Commit();
- Assert.That(transaction.Status == TransactionStatus.Committed, Is.True);
+ Assert.That(tx.Status == TransactionStatus.Committed, Is.True);
session2.Dispose();
session1.Dispose();
@@ -242,21 +248,23 @@ public void NewTransactionBeforeUsingStatelessSession()
{
var manager = Container.Resolve();
- var transactionManager = Container.Resolve();
- var transaction =
- transactionManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
- System.Transactions.IsolationLevel.Serializable);
+ var txManager = Container.Resolve();
+ var tx = txManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
+ System.Transactions.IsolationLevel.Serializable);
- transaction.Begin();
+ Assert.That(tx, Is.Not.Null);
+
+ tx.Begin();
var session = manager.OpenStatelessSession();
+
Assert.That(session, Is.Not.Null);
Assert.That(session.GetCurrentTransaction(), Is.Not.Null);
Assert.That(session.IsConnected, Is.True);
- transaction.Commit();
+ tx.Commit();
- Assert.That(transaction.Status == TransactionStatus.Committed, Is.True);
+ Assert.That(tx.Status == TransactionStatus.Committed, Is.True);
session.Dispose();
@@ -271,26 +279,29 @@ public void NewTransactionBeforeUsingStatelessSessionWithTwoDatabases()
{
var manager = Container.Resolve();
- var transactionManager = Container.Resolve();
- var transaction =
- transactionManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
- System.Transactions.IsolationLevel.Serializable);
+ var txManager = Container.Resolve();
- transaction.Begin();
+ var tx = txManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
+ System.Transactions.IsolationLevel.Serializable);
+ Assert.That(tx, Is.Not.Null);
+
+ tx.Begin();
var session1 = manager.OpenStatelessSession();
+
Assert.That(session1, Is.Not.Null);
Assert.That(session1.GetCurrentTransaction(), Is.Not.Null);
Assert.That(session1.IsConnected, Is.True);
var session2 = manager.OpenStatelessSession("db2");
+
Assert.That(session2, Is.Not.Null);
Assert.That(session2.GetCurrentTransaction(), Is.Not.Null);
Assert.That(session2.IsConnected, Is.True);
- transaction.Commit();
+ tx.Commit();
- Assert.That(transaction.Status == TransactionStatus.Committed, Is.True);
+ Assert.That(tx.Status == TransactionStatus.Committed, Is.True);
session2.Dispose();
session1.Dispose();
@@ -303,7 +314,8 @@ public void NonExistentAliasSession()
{
var manager = Container.Resolve();
- Assert.Throws(() => manager.OpenSession("something in the way she moves"));
+ Assert.Throws(
+ () => manager.OpenSession("something in the way she moves"));
}
[Test]
@@ -311,7 +323,8 @@ public void NonExistentAliasStatelessSession()
{
var manager = Container.Resolve();
- Assert.Throws(() => manager.OpenStatelessSession("something in the way she moves"));
+ Assert.Throws(
+ () => manager.OpenStatelessSession("something in the way she moves"));
}
[Test]
@@ -334,6 +347,7 @@ public void NonInterceptedSession()
session.Close();
var interceptor = Container.Resolve("nhibernate.session.interceptor.intercepted");
+
Assert.That(interceptor, Is.Not.Null);
Assert.That(interceptor.ConfirmOnSaveCall(), Is.False);
Assert.That(interceptor.ConfirmInstantiationCall(), Is.False);
@@ -350,12 +364,13 @@ public void SecondDatabaseSessionEnlistedOnlyOnceInActualTransaction()
{
var manager = Container.Resolve();
- var transactionManager = Container.Resolve();
- var transaction =
- transactionManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
- System.Transactions.IsolationLevel.Serializable);
+ var txManager = Container.Resolve();
- transaction.Begin();
+ var tx = txManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
+ System.Transactions.IsolationLevel.Serializable);
+ Assert.That(tx, Is.Not.Null);
+
+ tx.Begin();
// Open connection to first database and enlist session in running transaction.
var session1 = manager.OpenSession();
@@ -373,16 +388,16 @@ public void SecondDatabaseSessionEnlistedOnlyOnceInActualTransaction()
{
Assert.That(session3, Is.Not.Null);
- var transaction3 = session3.GetCurrentTransaction();
- Assert.That(transaction3, Is.Not.Null);
- Assert.That(transaction3.IsActive, Is.True);
+ var tx3 = session3.GetCurrentTransaction();
+ Assert.That(tx3, Is.Not.Null);
+ Assert.That(tx3.IsActive, Is.True);
}
Assert.That(session1.IsConnected, Is.True);
- transaction.Commit();
+ tx.Commit();
- Assert.That(transaction.Status == TransactionStatus.Committed, Is.True);
+ Assert.That(tx.Status == TransactionStatus.Committed, Is.True);
session1.Dispose();
@@ -398,12 +413,13 @@ public void SecondDatabaseStatelessSessionEnlistedOnlyOnceInActualTransaction()
{
var manager = Container.Resolve();
- var transactionManager = Container.Resolve();
- var transaction =
- transactionManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
- System.Transactions.IsolationLevel.Serializable);
+ var txManager = Container.Resolve();
+
+ var tx = txManager.CreateTransaction(System.Transactions.TransactionScopeOption.Required,
+ System.Transactions.IsolationLevel.Serializable);
+ Assert.That(tx, Is.Not.Null);
- transaction.Begin();
+ tx.Begin();
// Open connection to first database and enlist session in running transaction.
var session1 = manager.OpenStatelessSession();
@@ -421,16 +437,16 @@ public void SecondDatabaseStatelessSessionEnlistedOnlyOnceInActualTransaction()
{
Assert.That(session3, Is.Not.Null);
- var transaction3 = session3.GetCurrentTransaction();
- Assert.That(transaction3, Is.Not.Null);
- Assert.That(transaction3.IsActive, Is.True);
+ var tx3 = session3.GetCurrentTransaction();
+ Assert.That(tx3, Is.Not.Null);
+ Assert.That(tx3.IsActive, Is.True);
}
Assert.That(session1.IsConnected, Is.True);
- transaction.Commit();
+ tx.Commit();
- Assert.That(transaction.Status == TransactionStatus.Committed, Is.True);
+ Assert.That(tx.Status == TransactionStatus.Committed, Is.True);
session1.Dispose();
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/TwoDatabaseConfiguration.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/TwoDatabaseConfiguration.xml
index 31262b1ef..26fcd0005 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/TwoDatabaseConfiguration.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Internal/TwoDatabaseConfiguration.xml
@@ -16,7 +16,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
@@ -30,7 +30,7 @@
- Data Source=.; Initial Catalog=test2; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
@@ -44,7 +44,7 @@
- Data Source=.; Initial Catalog=test2; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
@@ -58,7 +58,7 @@
- Data Source=.; Initial Catalog=test2; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/InvalidConfigurationBuilder.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/InvalidConfigurationBuilder.xml
index 9d95008e5..cad109a4a 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/InvalidConfigurationBuilder.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/InvalidConfigurationBuilder.xml
@@ -10,7 +10,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities102/facility.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities102/facility.xml
index 64e5f9807..5f1b602fd 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities102/facility.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities102/facility.xml
@@ -16,7 +16,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
@@ -30,7 +30,7 @@
- Data Source=.; Initial Catalog=test2; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities103/Fixture.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities103/Fixture.cs
index 2f5808c49..8a70f1206 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities103/Fixture.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities103/Fixture.cs
@@ -17,7 +17,6 @@
namespace Castle.Facilities.NHibernateIntegration.Tests.Issues.Facilities103
{
using System;
- using System.Collections;
using System.Data;
using Castle.Facilities.NHibernateIntegration.SessionStores;
@@ -30,7 +29,7 @@ namespace Castle.Facilities.NHibernateIntegration.Tests.Issues.Facilities103
using NUnit.Framework;
- using ITransaction = Services.Transaction.ITransaction;
+ using ITransaction = Castle.Services.Transaction.ITransaction;
[TestFixture]
public class DefaultSessionManagerTestCase : IssueTestCase
@@ -40,20 +39,20 @@ public class DefaultSessionManagerTestCase : IssueTestCase
private const string Alias = "myAlias";
private const string InterceptorKey = DefaultSessionManager.InterceptorKey;
- private const string InterceptorKeyFormatString = DefaultSessionManager.InterceptorKeyFormatString;
+ private const string InterceptorKeyFormat = DefaultSessionManager.InterceptorKeyFormat;
private const System.Transactions.IsolationLevel DefaultTransactionIsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
private const IsolationLevel DefaultDataIsolationLevel = IsolationLevel.ReadUncommitted;
- private IKernel _kernel;
- private ITransactionManager _transactionManager;
- private ITransaction _transaction;
- private ISessionStore _sessionStore;
- private ISessionFactoryResolver _factoryResolver;
- private ISessionFactory _sessionFactory;
- private ISessionManager _sessionManager;
- private ISession _session;
- private IStatelessSession _statelessSession;
- private IDictionary _contextDictionary;
+ private IKernel _kernel = null!;
+ private ITransactionManager _transactionManager = null!;
+ private ITransaction _transaction = null!;
+ private IDictionary _transactionContext = null!;
+ private ISessionStore _sessionStore = null!;
+ private ISessionFactoryResolver _factoryResolver = null!;
+ private ISessionFactory _sessionFactory = null!;
+ private ISessionManager _sessionManager = null!;
+ private ISession _session = null!;
+ private IStatelessSession _statelessSession = null!;
protected override void OnSetUp()
{
@@ -62,10 +61,10 @@ protected override void OnSetUp()
_factoryResolver = new Mock().Object;
_transactionManager = new Mock().Object;
_transaction = new Mock().Object;
+ _transactionContext = new Dictionary();
_sessionFactory = new Mock().Object;
_session = new Mock().Object;
_statelessSession = new Mock().Object;
- _contextDictionary = new Hashtable();
_sessionManager = new DefaultSessionManager(_kernel, _sessionStore, _factoryResolver);
}
@@ -74,13 +73,13 @@ public void WhenBeginTransactionFailsSessionIsRemovedFromSessionStore()
{
Mock.Get(_kernel).Setup(x => x.Resolve()).Returns(_transactionManager);
Mock.Get(_transactionManager).Setup(x => x.CurrentTransaction).Returns(_transaction);
+ Mock.Get(_transaction).Setup(x => x.IsolationLevel).Returns(DefaultTransactionIsolationLevel);
+ Mock.Get(_transaction).Setup(x => x.Context).Returns(_transactionContext);
Mock.Get(_factoryResolver).Setup(x => x.GetSessionFactory(Alias)).Returns(_sessionFactory);
- Mock.Get(_kernel).Setup(x => x.HasComponent(string.Format(InterceptorKeyFormatString, Alias))).Returns(false);
+ Mock.Get(_kernel).Setup(x => x.HasComponent(string.Format(InterceptorKeyFormat, Alias))).Returns(false);
Mock.Get(_kernel).Setup(x => x.HasComponent(InterceptorKey)).Returns(false);
Mock.Get(_sessionFactory).Setup(x => x.OpenSession()).Returns(_session);
_session.FlushMode = _sessionManager.DefaultFlushMode;
- Mock.Get(_transaction).Setup(x => x.IsolationLevel).Returns(DefaultTransactionIsolationLevel);
- Mock.Get(_transaction).Setup(x => x.Context).Returns(_contextDictionary);
Mock.Get(_session).Setup(x => x.BeginTransaction(DefaultDataIsolationLevel)).Throws(new Exception());
try
@@ -107,7 +106,7 @@ public void WhenBeginTransactionFailsStatelessSessionIsRemovedFromSessionStore()
Mock.Get(_factoryResolver).Setup(x => x.GetSessionFactory(Alias)).Returns(_sessionFactory);
Mock.Get(_sessionFactory).Setup(x => x.OpenStatelessSession()).Returns(_statelessSession);
Mock.Get(_transaction).Setup(x => x.IsolationLevel).Returns(DefaultTransactionIsolationLevel);
- Mock.Get(_transaction).Setup(x => x.Context).Returns(_contextDictionary);
+ Mock.Get(_transaction).Setup(x => x.Context).Returns(_transactionContext);
Mock.Get(_statelessSession).Setup(x => x.BeginTransaction(DefaultDataIsolationLevel)).Throws(new Exception());
try
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities106/Fixture.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities106/Fixture.cs
index e59b0949a..901cbd3a8 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities106/Fixture.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities106/Fixture.cs
@@ -16,9 +16,8 @@
namespace Castle.Facilities.NHibernateIntegration.Tests.Issues.Facilities106
{
- using Builders;
-
- using Core.Configuration;
+ using Castle.Core.Configuration;
+ using Castle.Facilities.NHibernateIntegration.Builders;
using NUnit.Framework;
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities106/factory1.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities106/factory1.xml
index 51eb72829..0578d682e 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities106/factory1.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities106/factory1.xml
@@ -4,7 +4,7 @@
DummyProvider
NHibernate.Driver.Sql2008ClientDriver
- NHibernate.Dialect.MsSql2008Dialect
+ NHibernate.Dialect.MsSql2012Dialect
Data Source=.; Initial Catalog=test; Integrated Security=SSPI
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities112/Fixture.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities112/Fixture.cs
index a50688e81..f9331cd7f 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities112/Fixture.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities112/Fixture.cs
@@ -46,15 +46,17 @@ public virtual void SessionFactoryIsLazilyInitialized()
{
var handler = Container.Kernel.GetHandler("sessionFactory1");
+ const BindingFlags BindingFlags = BindingFlags.NonPublic |
+ BindingFlags.Instance |
+ BindingFlags.GetField;
+
var lifestyleManagerField =
- typeof(DefaultHandler).GetField("lifestyleManager",
- BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField);
+ typeof(DefaultHandler).GetField("lifestyleManager", BindingFlags)!;
var lifeStyleManager = lifestyleManagerField.GetValue(handler) as SingletonLifestyleManager;
Assert.That(lifeStyleManager, Is.Not.Null);
var instanceField =
- typeof(SingletonLifestyleManager).GetField("instance",
- BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField);
+ typeof(SingletonLifestyleManager).GetField("instance", BindingFlags)!;
var instance = instanceField.GetValue(lifeStyleManager);
Assert.That(instance, Is.Null);
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities113/Fixture.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities113/Fixture.cs
index 96884ac57..fe2711a71 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities113/Fixture.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities113/Fixture.cs
@@ -16,7 +16,7 @@
namespace Castle.Facilities.NHibernateIntegration.Tests.Issues.Facilities113
{
- using MicroKernel.Registration;
+ using Castle.MicroKernel.Registration;
using Moq;
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities116/Fixture.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities116/Fixture.cs
index ba8ca79d8..dc43280a0 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities116/Fixture.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities116/Fixture.cs
@@ -21,20 +21,16 @@ namespace Castle.Facilities.NHibernateIntegration.Tests.Issues.Facilities116
using System.IO;
using System.Threading;
- using Builders;
-
+ using Castle.Core.Configuration;
+ using Castle.Core.Resource;
+ using Castle.Facilities.NHibernateIntegration.Builders;
using Castle.Facilities.NHibernateIntegration.Persisters;
using Castle.MicroKernel;
-
- using Core.Configuration;
- using Core.Resource;
-
- using MicroKernel.SubSystems.Configuration;
+ using Castle.MicroKernel.SubSystems.Configuration;
+ using Castle.Windsor.Configuration.Interpreters;
using NUnit.Framework;
- using Windsor.Configuration.Interpreters;
-
using Configuration = NHibernate.Cfg.Configuration;
[TestFixture]
@@ -45,8 +41,8 @@ public class Fixture : IssueTestCase
private readonly Func> _objectPersister =
ObjectPersisterFactory.Create;
- private IConfiguration _facilityConfiguration;
- private IConfigurationBuilder _configurationBuilder;
+ private IConfiguration _facilityConfiguration = null!;
+ private IConfigurationBuilder _configurationBuilder = null!;
protected override string ConfigurationFile =>
"EmptyConfiguration.xml";
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities116/facility.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities116/facility.xml
index ee5aeac1b..b67de0466 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities116/facility.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities116/facility.xml
@@ -16,7 +16,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities117/PersistentConfigurationBuilderConventionsFixture.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities117/PersistentConfigurationBuilderConventionsFixture.cs
index ad44bee2d..b43c9159e 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities117/PersistentConfigurationBuilderConventionsFixture.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities117/PersistentConfigurationBuilderConventionsFixture.cs
@@ -19,21 +19,17 @@ namespace Castle.Facilities.NHibernateIntegration.Tests.Issues.Facilities117
using System;
using System.Collections.Generic;
- using Builders;
-
+ using Castle.Core.Configuration;
+ using Castle.Core.Resource;
+ using Castle.Facilities.NHibernateIntegration.Builders;
using Castle.MicroKernel;
-
- using Core.Configuration;
- using Core.Resource;
-
- using MicroKernel.SubSystems.Configuration;
+ using Castle.MicroKernel.SubSystems.Configuration;
+ using Castle.Windsor.Configuration.Interpreters;
using Moq;
using NUnit.Framework;
- using Windsor.Configuration.Interpreters;
-
[TestFixture]
public class PersistentConfigurationBuilderConventionsFixture
{
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities117/facility.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities117/facility.xml
index 4800623bb..78461da9f 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities117/facility.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities117/facility.xml
@@ -10,7 +10,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities119/TestConfigurationBuilder2.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities119/TestConfigurationBuilder2.cs
index a9d1ae1b3..6bf996564 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities119/TestConfigurationBuilder2.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities119/TestConfigurationBuilder2.cs
@@ -16,7 +16,7 @@
namespace Castle.Facilities.NHibernateIntegration.Tests.Issues.Facilities119
{
- using Core.Configuration;
+ using Castle.Core.Configuration;
using NHibernate.Cfg;
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities119/TestConfigurationBuilder3.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities119/TestConfigurationBuilder3.cs
index 2d6781468..f532d798b 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities119/TestConfigurationBuilder3.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities119/TestConfigurationBuilder3.cs
@@ -16,7 +16,7 @@
namespace Castle.Facilities.NHibernateIntegration.Tests.Issues.Facilities119
{
- using Core.Configuration;
+ using Castle.Core.Configuration;
using NHibernate.Cfg;
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities119/facility.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities119/facility.xml
index 61cff75d5..75347b946 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities119/facility.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities119/facility.xml
@@ -11,7 +11,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
Castle.Facilities.NHibernateIntegration.Tests
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities152/facilitynonweb.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities152/facilitynonweb.xml
index 376346546..d6282ef41 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities152/facilitynonweb.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities152/facilitynonweb.xml
@@ -11,7 +11,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities152/facilityweb.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities152/facilityweb.xml
index 7eb10cd0a..e63e2cb54 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities152/facilityweb.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities152/facilityweb.xml
@@ -11,7 +11,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/IssueTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/IssueTestCase.cs
index 90d8efe3e..1f13a393d 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/IssueTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Issues/IssueTestCase.cs
@@ -22,7 +22,7 @@ protected virtual string BugNumber
{
get
{
- var ns = GetType().Namespace;
+ var ns = GetType().Namespace!;
return ns[(ns.LastIndexOf('.') + 1)..];
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/MinimalConfiguration.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/MinimalConfiguration.xml
index c6e529471..41e1bc2be 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/MinimalConfiguration.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/MinimalConfiguration.xml
@@ -10,7 +10,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Program.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Program.cs
index c38d97609..33b51507a 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Program.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Program.cs
@@ -14,8 +14,6 @@
// limitations under the License.
#endregion
-using System;
-
using NUnit.Common;
using NUnitLite;
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Registration/FacilityFluentConfigTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Registration/FacilityFluentConfigTestCase.cs
index 2cc306b96..3e2f6a8bf 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Registration/FacilityFluentConfigTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Registration/FacilityFluentConfigTestCase.cs
@@ -138,27 +138,27 @@ public Configuration GetConfiguration(IConfiguration facilityConfiguration)
internal class DummySessionStore : ISessionStore
{
- public SessionDelegate FindCompatibleSession(string alias)
+ public bool IsCurrentActivityEmptyFor(string? alias)
{
throw new System.NotImplementedException();
}
- public StatelessSessionDelegate FindCompatibleStatelessSession(string alias)
+ public SessionDelegate? FindCompatibleSession(string? alias)
{
throw new System.NotImplementedException();
}
- public bool IsCurrentActivityEmptyFor(string alias)
+ public void Store(string alias, SessionDelegate session)
{
throw new System.NotImplementedException();
}
- public void Store(string alias, SessionDelegate session)
+ public void Remove(SessionDelegate session)
{
throw new System.NotImplementedException();
}
- public void Remove(SessionDelegate session)
+ public StatelessSessionDelegate? FindCompatibleStatelessSession(string? alias)
{
throw new System.NotImplementedException();
}
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/SessionCreation/DaoTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/SessionCreation/DaoTestCase.cs
index 1e43f2137..971acf85a 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/SessionCreation/DaoTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/SessionCreation/DaoTestCase.cs
@@ -16,7 +16,7 @@
namespace Castle.Facilities.NHibernateIntegration.Tests.SessionCreation
{
- using MicroKernel.Registration;
+ using Castle.MicroKernel.Registration;
using NUnit.Framework;
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/SessionCreation/MyDao.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/SessionCreation/MyDao.cs
index 64771375d..fd03f91fd 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/SessionCreation/MyDao.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/SessionCreation/MyDao.cs
@@ -34,6 +34,7 @@ public MyDao(ISessionManager sessionManager, MySecondDao otherDao)
public void PerformComplexOperation1()
{
using var session = _sessionManager.OpenSession();
+
Assert.That(session, Is.Not.Null);
_otherDao.PerformSimpleOperation(session);
@@ -41,7 +42,7 @@ public void PerformComplexOperation1()
public void PerformComplexOperation2()
{
- ISession previousSession = null;
+ ISession? previousSession = null;
using (var session = _sessionManager.OpenSession())
{
@@ -54,10 +55,12 @@ public void PerformComplexOperation2()
public void DoOpenCloseAndDisposeOperation()
{
using var session = _sessionManager.OpenSession();
+
Assert.That(session.IsConnected, Is.True);
Assert.That(session.IsOpen, Is.True);
session.Close();
+
Assert.That(session.IsConnected, Is.False);
Assert.That(session.IsOpen, Is.False);
}
@@ -65,6 +68,7 @@ public void DoOpenCloseAndDisposeOperation()
public void PerformComplexStatelessOperation1()
{
using var session = _sessionManager.OpenStatelessSession();
+
Assert.That(session, Is.Not.Null);
_otherDao.PerformSimpleStatelessOperation(session);
@@ -72,7 +76,7 @@ public void PerformComplexStatelessOperation1()
public void PerformComplexStatelessOperation2()
{
- IStatelessSession previousSession = null;
+ IStatelessSession? previousSession = null;
using (var session = _sessionManager.OpenStatelessSession())
{
@@ -85,10 +89,12 @@ public void PerformComplexStatelessOperation2()
public void DoStatelessOpenCloseAndDisposeOperation()
{
using var session = _sessionManager.OpenStatelessSession();
+
Assert.That(session.IsConnected, Is.True);
Assert.That(session.IsOpen, Is.True);
session.Close();
+
Assert.That(session.IsConnected, Is.False);
Assert.That(session.IsOpen, Is.False);
}
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/SessionCreation/MySecondDao.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/SessionCreation/MySecondDao.cs
index 535a15e98..63401937b 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/SessionCreation/MySecondDao.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/SessionCreation/MySecondDao.cs
@@ -34,6 +34,7 @@ public void PerformSimpleOperation(ISession previousSession)
Assert.That(previousSession, Is.Not.Null);
using var session = _sessionManager.OpenSession();
+
Assert.That(session, Is.Not.Null);
Assert.That(SessionDelegate.AreEqual(session, previousSession), Is.True);
}
@@ -43,6 +44,7 @@ public void PerformSimpleOperation2(ISession previousSession)
Assert.That(previousSession, Is.Not.Null);
using var session = _sessionManager.OpenSession();
+
Assert.That(session, Is.Not.Null);
Assert.That(ReferenceEquals(session, previousSession), Is.False);
}
@@ -52,6 +54,7 @@ public void PerformSimpleStatelessOperation(IStatelessSession previousSession)
Assert.That(previousSession, Is.Not.Null);
using var session = _sessionManager.OpenStatelessSession();
+
Assert.That(session, Is.Not.Null);
Assert.That(StatelessSessionDelegate.AreEqual(session, previousSession), Is.True);
}
@@ -61,6 +64,7 @@ public void PerformSimpleStatelessOperation2(IStatelessSession previousSession)
Assert.That(previousSession, Is.Not.Null);
using var session = _sessionManager.OpenStatelessSession();
+
Assert.That(session, Is.Not.Null);
Assert.That(ReferenceEquals(session, previousSession), Is.False);
}
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/SessionManagementInterceptorsTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/SessionManagementInterceptorsTestCase.cs
index d487b0c84..7a123bb15 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/SessionManagementInterceptorsTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/SessionManagementInterceptorsTestCase.cs
@@ -16,9 +16,9 @@
namespace Castle.Facilities.NHibernateIntegration.Tests
{
- using Common;
+ using Castle.MicroKernel.Registration;
- using MicroKernel.Registration;
+ using Common;
using NUnit.Framework;
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/TestConfigurationBuilder.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/TestConfigurationBuilder.cs
index 141b84b1c..f41b23a00 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/TestConfigurationBuilder.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/TestConfigurationBuilder.cs
@@ -19,9 +19,8 @@ namespace Castle.Facilities.NHibernateIntegration.Tests
using System.Configuration;
using System.IO;
- using Builders;
-
- using Core.Configuration;
+ using Castle.Core.Configuration;
+ using Castle.Facilities.NHibernateIntegration.Builders;
using NUnit.Framework;
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/DistributedTransactionsTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/DistributedTransactionsTestCase.cs
index 3ce5f7658..87bbfe24b 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/DistributedTransactionsTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/DistributedTransactionsTestCase.cs
@@ -14,18 +14,17 @@
// limitations under the License.
#endregion
+#if NETFRAMEWORK
namespace Castle.Facilities.NHibernateIntegration.Tests.Transactions
{
-#if NETFRAMEWORK
using System;
using System.Transactions;
- using MicroKernel.Registration;
+ using Castle.MicroKernel.Registration;
+ using Castle.Services.Transaction;
using NUnit.Framework;
- using Services.Transaction;
-
[TestFixture]
public class DistributedTransactionsTestCase : AbstractNHibernateTestCase
{
@@ -182,5 +181,5 @@ public void ExceptionOnEndWithTwoDatabasesStateless()
Assert.That(orders.Length, Is.EqualTo(0));
}
}
-#endif
}
+#endif
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/FirstDao.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/FirstDao.cs
index baaa8c019..ec8d788bf 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/FirstDao.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/FirstDao.cs
@@ -42,8 +42,8 @@ public virtual Blog Create()
public virtual Blog Create(string name)
{
using var session = _sessionManager.OpenSession();
- var transaction = session.GetCurrentTransaction();
+ var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
Assert.That(transaction.IsActive, Is.True);
@@ -51,6 +51,7 @@ public virtual Blog Create(string name)
{
Name = name
};
+
session.Save(blog);
return blog;
@@ -60,8 +61,8 @@ public virtual Blog Create(string name)
public virtual void Delete(string name)
{
using var session = _sessionManager.OpenSession();
- var transaction = session.GetCurrentTransaction();
+ var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
session.Delete($"from Blog b where b.Name ='{name}'");
@@ -71,6 +72,7 @@ public virtual void Delete(string name)
public virtual void AddBlogRef(BlogRef blogRef)
{
using var session = _sessionManager.OpenSession();
+
session.Save(blogRef);
}
@@ -84,8 +86,8 @@ public virtual Blog CreateStateless()
public virtual Blog CreateStateless(string name)
{
using var session = _sessionManager.OpenStatelessSession();
- var transaction = session.GetCurrentTransaction();
+ var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
Assert.That(transaction.IsActive, Is.True);
@@ -93,7 +95,9 @@ public virtual Blog CreateStateless(string name)
{
Name = name
};
+
session.Insert(blog);
+
return blog;
}
@@ -101,8 +105,8 @@ public virtual Blog CreateStateless(string name)
public virtual void DeleteStateless(string name)
{
using var session = _sessionManager.OpenStatelessSession();
- var transaction = session.GetCurrentTransaction();
+ var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
session.Delete($"from Blog b where b.Name ='{name}'");
@@ -111,6 +115,7 @@ public virtual void DeleteStateless(string name)
public virtual void AddBlogRefStateless(BlogRef blogRef)
{
using var session = _sessionManager.OpenStatelessSession();
+
session.Insert(blogRef);
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/FirstDao2.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/FirstDao2.cs
index 24a1773f6..21c0d7c35 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/FirstDao2.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/FirstDao2.cs
@@ -16,7 +16,7 @@
namespace Castle.Facilities.NHibernateIntegration.Tests.Transactions
{
- using Services.Transaction;
+ using Castle.Services.Transaction;
[Transactional]
public class FirstDao2
@@ -38,11 +38,14 @@ public virtual Blog Create()
public virtual Blog Create(string name)
{
using var session = _sessionManager.OpenSession();
+
var blog = new Blog
{
Name = name
};
+
session.Save(blog);
+
return blog;
}
@@ -56,11 +59,14 @@ public virtual Blog CreateStateless()
public virtual Blog CreateStateless(string name)
{
using var session = _sessionManager.OpenStatelessSession();
+
var blog = new Blog
{
Name = name
};
+
session.Insert(blog);
+
return blog;
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/OrderDao.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/OrderDao.cs
index 9c00c6d9c..f3194ce4f 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/OrderDao.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/OrderDao.cs
@@ -16,14 +16,13 @@
namespace Castle.Facilities.NHibernateIntegration.Tests.Transactions
{
- using NHibernate;
+ using Castle.Facilities.NHibernateIntegration.Components.Dao;
+ using Castle.Services.Transaction;
- using NHibernateIntegration.Components.Dao;
+ using NHibernate;
using NUnit.Framework;
- using Services.Transaction;
-
[Transactional]
public class OrderDao : NHibernateGenericDao
{
@@ -38,6 +37,7 @@ public OrderDao(ISessionManager sessionManager) : base(sessionManager, "db2")
public virtual Order Create(float val)
{
using var session = _sessionManager.OpenSession("db2");
+
var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
@@ -45,6 +45,7 @@ public virtual Order Create(float val)
{
Value = val
};
+
session.Save(order);
return order;
@@ -54,6 +55,7 @@ public virtual Order Create(float val)
public virtual void Update(Order order, float newval)
{
using var session = _sessionManager.OpenSession("db2");
+
var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
@@ -66,6 +68,7 @@ public virtual void Update(Order order, float newval)
public virtual void Delete(int orderId)
{
using var session = _sessionManager.OpenSession("db2");
+
var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
@@ -78,6 +81,7 @@ public virtual void Delete(int orderId)
public virtual Order CreateStateless(float val)
{
using var session = _sessionManager.OpenStatelessSession("db2");
+
var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
@@ -85,6 +89,7 @@ public virtual Order CreateStateless(float val)
{
Value = val
};
+
session.Insert(order);
return order;
@@ -94,6 +99,7 @@ public virtual Order CreateStateless(float val)
public virtual void UpdateStateless(Order order, float newval)
{
using var session = _sessionManager.OpenStatelessSession("db2");
+
var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
@@ -106,6 +112,7 @@ public virtual void UpdateStateless(Order order, float newval)
public virtual void DeleteStateless(int orderId)
{
using var session = _sessionManager.OpenStatelessSession("db2");
+
var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/OrderDao2.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/OrderDao2.cs
index 814b154d8..862213ef1 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/OrderDao2.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/OrderDao2.cs
@@ -16,14 +16,13 @@
namespace Castle.Facilities.NHibernateIntegration.Tests.Transactions
{
- using NHibernate;
+ using Castle.Facilities.NHibernateIntegration.Components.Dao;
+ using Castle.Services.Transaction;
- using NHibernateIntegration.Components.Dao;
+ using NHibernate;
using NUnit.Framework;
- using Services.Transaction;
-
[Transactional]
public class OrderDao2 : NHibernateGenericDao
{
@@ -38,6 +37,7 @@ public OrderDao2(ISessionManager sessionManager) : base(sessionManager, "db2")
public virtual Order Create(float val)
{
using var session = _sessionManager.OpenSession("db2");
+
var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
@@ -45,6 +45,7 @@ public virtual Order Create(float val)
{
Value = val
};
+
session.Save(order);
return order;
@@ -54,6 +55,7 @@ public virtual Order Create(float val)
public virtual Order CreateStateless(float val)
{
using var session = _sessionManager.OpenStatelessSession("db2");
+
var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
@@ -61,6 +63,7 @@ public virtual Order CreateStateless(float val)
{
Value = val
};
+
session.Insert(order);
return order;
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/RootService.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/RootService.cs
index c6feb25c5..72372095b 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/RootService.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/RootService.cs
@@ -18,11 +18,10 @@ namespace Castle.Facilities.NHibernateIntegration.Tests.Transactions
{
using System;
- using NHibernate.Criterion;
-
- using NHibernateIntegration.Components.Dao;
+ using Castle.Facilities.NHibernateIntegration.Components.Dao;
+ using Castle.Services.Transaction;
- using Services.Transaction;
+ using NHibernate.Criterion;
[Transactional]
public class RootService : NHibernateGenericDao
@@ -30,14 +29,14 @@ public class RootService : NHibernateGenericDao
private readonly FirstDao _firstDao;
private readonly SecondDao _secondDao;
- public RootService(FirstDao firstDao, SecondDao secondDao, ISessionManager sessionManager) :
+ public RootService(ISessionManager sessionManager, FirstDao firstDao, SecondDao secondDao) :
base(sessionManager)
{
_firstDao = firstDao;
_secondDao = secondDao;
}
- public OrderDao OrderDao { get; set; }
+ public OrderDao OrderDao { get; set; } = null!;
[Transaction]
public virtual Blog CreateBlogUsingDetachedCriteria(string name)
@@ -49,7 +48,6 @@ public virtual Blog CreateBlogUsingDetachedCriteria(string name)
public virtual Blog FindBlogUsingDetachedCriteria(string name)
{
var dc = DetachedCriteria.For();
- //dc.Add(Property.ForName("Name").Eq(name));
dc.Add(Property.ForName(nameof(Blog.Name)).Eq(name));
var session = SessionManager.OpenSession();
@@ -60,6 +58,7 @@ public virtual Blog FindBlogUsingDetachedCriteria(string name)
public virtual BlogItem SuccessfulCall()
{
var blog = _firstDao.Create();
+
return _secondDao.Create(blog);
}
@@ -67,6 +66,7 @@ public virtual BlogItem SuccessfulCall()
public virtual void CallWithException()
{
var blog = _firstDao.Create();
+
_secondDao.CreateWithException(blog);
}
@@ -74,6 +74,7 @@ public virtual void CallWithException()
public virtual void CallWithException2()
{
var blog = _firstDao.Create();
+
_secondDao.CreateWithException2(blog);
}
@@ -85,6 +86,7 @@ public virtual void DoBlogRefOperation(Blog blog)
ParentBlog = blog,
Title = "title"
};
+
_firstDao.AddBlogRef(blogRef);
_firstDao.Delete("Blog1");
@@ -94,7 +96,9 @@ public virtual void DoBlogRefOperation(Blog blog)
public virtual void TwoDbOperationCreate(bool throwException)
{
var blog = _firstDao.Create();
+
_secondDao.Create(blog);
+
OrderDao.Create(1.122f);
if (throwException)
@@ -113,7 +117,6 @@ public virtual Blog CreateBlogStatelessUsingDetachedCriteria(string name)
public virtual Blog FindBlogStatelessUsingDetachedCriteria(string name)
{
var dc = DetachedCriteria.For();
- //dc.Add(Property.ForName("Name").Eq(name));
dc.Add(Property.ForName(nameof(Blog.Name)).Eq(name));
var session = SessionManager.OpenStatelessSession();
@@ -149,6 +152,7 @@ public virtual void DoBlogRefOperationStateless(Blog blog)
ParentBlog = blog,
Title = "title"
};
+
_firstDao.AddBlogRefStateless(blogRef);
_firstDao.DeleteStateless("Blog1");
@@ -158,7 +162,9 @@ public virtual void DoBlogRefOperationStateless(Blog blog)
public virtual void TwoDbOperationCreateStateless(bool throwException)
{
var blog = _firstDao.CreateStateless();
+
_secondDao.CreateStateless(blog);
+
OrderDao.CreateStateless(1.122f);
if (throwException)
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/RootService2.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/RootService2.cs
index c000a4308..d0c838220 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/RootService2.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/RootService2.cs
@@ -18,9 +18,9 @@ namespace Castle.Facilities.NHibernateIntegration.Tests.Transactions
{
using System;
- using NHibernateIntegration.Components.Dao;
+ using Castle.Facilities.NHibernateIntegration.Components.Dao;
- using Services.Transaction;
+ using Castle.Services.Transaction;
[Transactional]
public class RootService2 : NHibernateGenericDao
@@ -28,20 +28,22 @@ public class RootService2 : NHibernateGenericDao
private readonly FirstDao2 _firstDao;
private readonly SecondDao2 _secondDao;
- public RootService2(FirstDao2 firstDao, SecondDao2 secondDao, ISessionManager sessionManager) :
+ public RootService2(ISessionManager sessionManager, FirstDao2 firstDao, SecondDao2 secondDao) :
base(sessionManager)
{
_firstDao = firstDao;
_secondDao = secondDao;
}
- public OrderDao2 OrderDao { get; set; }
+ public OrderDao2 OrderDao { get; set; } = null!;
[Transaction(IsDistributed = true)]
public virtual void TwoDbOperationCreate(bool throwException)
{
var blog = _firstDao.Create();
+
_secondDao.Create(blog);
+
OrderDao.Create(1.122f);
if (throwException)
@@ -54,7 +56,9 @@ public virtual void TwoDbOperationCreate(bool throwException)
public virtual void TwoDbOperationCreateStateless(bool throwException)
{
var blog = _firstDao.CreateStateless();
+
_secondDao.CreateStateless(blog);
+
OrderDao.CreateStateless(1.122f);
if (throwException)
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/SecondDao.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/SecondDao.cs
index d0a74acbd..a00ca5271 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/SecondDao.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/SecondDao.cs
@@ -38,6 +38,7 @@ public SecondDao(ISessionManager sessionManager)
public virtual BlogItem Create(Blog blog)
{
using var session = _sessionManager.OpenSession();
+
var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
@@ -48,6 +49,7 @@ public virtual BlogItem Create(Blog blog)
Text = "x",
DateTime = DateTime.Now,
};
+
session.Save(item);
return item;
@@ -57,6 +59,7 @@ public virtual BlogItem Create(Blog blog)
public virtual BlogItem CreateWithException(Blog blog)
{
using var session = _sessionManager.OpenSession();
+
var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
@@ -75,8 +78,8 @@ public virtual BlogItem CreateWithException(Blog blog)
public virtual BlogItem CreateWithException2(Blog blog)
{
using var session = _sessionManager.OpenSession();
- var transaction = session.GetCurrentTransaction();
+ var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
var item = new BlogItem
@@ -95,8 +98,8 @@ public virtual BlogItem CreateWithException2(Blog blog)
public virtual BlogItem CreateStateless(Blog blog)
{
using var session = _sessionManager.OpenStatelessSession();
- var transaction = session.GetCurrentTransaction();
+ var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
var item = new BlogItem
@@ -106,6 +109,7 @@ public virtual BlogItem CreateStateless(Blog blog)
Text = "x",
DateTime = DateTime.Now,
};
+
session.Insert(item);
return item;
@@ -115,8 +119,8 @@ public virtual BlogItem CreateStateless(Blog blog)
public virtual BlogItem CreateWithExceptionStateless(Blog blog)
{
using var session = _sessionManager.OpenStatelessSession();
- var transaction = session.GetCurrentTransaction();
+ var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
var item = new BlogItem
@@ -134,8 +138,8 @@ public virtual BlogItem CreateWithExceptionStateless(Blog blog)
public virtual BlogItem CreateWithExceptionStateless2(Blog blog)
{
using var session = _sessionManager.OpenStatelessSession();
- var transaction = session.GetCurrentTransaction();
+ var transaction = session.GetCurrentTransaction();
Assert.That(transaction, Is.Not.Null);
var item = new BlogItem
@@ -145,6 +149,7 @@ public virtual BlogItem CreateWithExceptionStateless2(Blog blog)
Text = "x",
DateTime = DateTime.Now,
};
+
session.Insert(item);
throw new NotSupportedException("I don't feel like supporting this");
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/SecondDao2.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/SecondDao2.cs
index 38b306ad7..08fb9fece 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/SecondDao2.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/Model/SecondDao2.cs
@@ -30,6 +30,7 @@ public SecondDao2(ISessionManager sessionManager)
public BlogItem Create(Blog blog)
{
using var session = _sessionManager.OpenSession();
+
var item = new BlogItem
{
ParentBlog = blog,
@@ -37,6 +38,7 @@ public BlogItem Create(Blog blog)
Text = "x",
DateTime = DateTime.Now,
};
+
session.Save(item);
return item;
@@ -45,6 +47,7 @@ public BlogItem Create(Blog blog)
public BlogItem CreateStateless(Blog blog)
{
using var session = _sessionManager.OpenStatelessSession();
+
var item = new BlogItem
{
ParentBlog = blog,
@@ -52,6 +55,7 @@ public BlogItem CreateStateless(Blog blog)
Text = "x",
DateTime = DateTime.Now,
};
+
session.Insert(item);
return item;
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/TransactionWithTwoDatabasesTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/TransactionWithTwoDatabasesTestCase.cs
index cf2d5bd8f..8bbb44ef5 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/TransactionWithTwoDatabasesTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/TransactionWithTwoDatabasesTestCase.cs
@@ -55,6 +55,7 @@ public void SuccessfulSituationWithTwoDatabases()
Assert.That(blogItems, Has.Length.EqualTo(1));
Assert.That(orders, Has.Length.EqualTo(1));
}
+
[Test]
public void ExceptionOnEndWithTwoDatabases()
{
@@ -82,7 +83,6 @@ public void ExceptionOnEndWithTwoDatabases()
Assert.That(orders.Length, Is.EqualTo(0));
}
-
[Test]
public void SuccessfulSituationWithTwoDatabasesStateless()
{
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/TransactionsTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/TransactionsTestCase.cs
index f58186e20..2ce7fc5da 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/TransactionsTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/TransactionsTestCase.cs
@@ -36,7 +36,7 @@ protected override void ConfigureContainer()
}
[Test]
- public void TestTransaction()
+ public void FailedTestTransaction()
{
var service = Container.Resolve();
var dao = Container.Resolve("myfirstdao");
@@ -57,7 +57,7 @@ public void TestTransaction()
}
[Test]
- public void TestTransactionStateless()
+ public void FailedTestTransactionStateless()
{
var service = Container.Resolve();
var dao = Container.Resolve("myfirstdao");
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/TwoDatabaseConfiguration.xml b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/TwoDatabaseConfiguration.xml
index b8c7fc552..aca5f5680 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/TwoDatabaseConfiguration.xml
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Transactions/TwoDatabaseConfiguration.xml
@@ -18,7 +18,7 @@
- Data Source=.; Initial Catalog=test; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
@@ -32,7 +32,7 @@
- Data Source=.; Initial Catalog=test2; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
@@ -46,7 +46,7 @@
- Data Source=.; Initial Catalog=test2; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
@@ -60,7 +60,7 @@
- Data Source=.; Initial Catalog=test2; Integrated Security=SSPI
- NHibernate.Connection.DriverConnectionProvider
- NHibernate.Driver.Sql2008ClientDriver
- - NHibernate.Dialect.MsSql2008Dialect
+ - NHibernate.Dialect.MsSql2012Dialect
diff --git a/src/Castle.Facilities.NHibernateIntegration.Tests/Wiring/DaoTestCase.cs b/src/Castle.Facilities.NHibernateIntegration.Tests/Wiring/DaoTestCase.cs
index b2c39cefa..30f76c0db 100644
--- a/src/Castle.Facilities.NHibernateIntegration.Tests/Wiring/DaoTestCase.cs
+++ b/src/Castle.Facilities.NHibernateIntegration.Tests/Wiring/DaoTestCase.cs
@@ -16,7 +16,7 @@
namespace Castle.Facilities.NHibernateIntegration.Tests.Wiring
{
- using MicroKernel.Registration;
+ using Castle.MicroKernel.Registration;
using NUnit.Framework;
diff --git a/src/Castle.Facilities.NHibernateIntegration/Builders/DefaultConfigurationBuilder.cs b/src/Castle.Facilities.NHibernateIntegration/Builders/DefaultConfigurationBuilder.cs
index 65c03da08..575bbc80c 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Builders/DefaultConfigurationBuilder.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Builders/DefaultConfigurationBuilder.cs
@@ -21,7 +21,7 @@ namespace Castle.Facilities.NHibernateIntegration.Builders
using System.IO;
using System.Reflection;
- using Core.Configuration;
+ using Castle.Core.Configuration;
using NHibernate.Event;
@@ -82,7 +82,7 @@ protected static void RegisterResources(Configuration configuration, IConfigurat
foreach (var item in facilityConfiguration.Children)
{
- var name = item.Attributes["name"];
+ var name = item.Attributes["name"]!;
var assemblyName = item.Attributes["assembly"];
if (assemblyName != null)
{
@@ -109,15 +109,15 @@ protected static void RegisterListeners(Configuration configuration, IConfigurat
foreach (var item in facilityConfiguration.Children)
{
- var eventName = item.Attributes["event"];
- var typeName = item.Attributes["type"];
+ var eventName = item.Attributes["event"]!;
+ var typeName = item.Attributes["type"]!;
if (!Enum.IsDefined(typeof(ListenerType), eventName))
{
throw new ConfigurationErrorsException("An invalid listener type was specified.");
}
- var classType = Type.GetType(typeName);
+ var classType = Type.GetType(typeName)!;
//if (classType == null)
// throw new ConfigurationErrorsException("The full type name of the listener class must be specified.");
@@ -170,16 +170,19 @@ protected static void GenerateMappingFromAttributesIfNeeded(Configuration config
// If assembly "NHibernate.Mapping.Attributes" is referenced in targetAssembly.
if (Array.Exists(referencedAssemblies,
- (AssemblyName x) => string.Equals(x.Name, NHibernateMappingAttributesAssemblyName, StringComparison.Ordinal)))
+ (AssemblyName assemblyName) =>
+ string.Equals(assemblyName.Name,
+ NHibernateMappingAttributesAssemblyName,
+ StringComparison.Ordinal)))
{
// Obtains, by reflection, the necessary tools to generate NHibernate mapping from attributes.
var hbmSerializerType =
Type.GetType(string.Concat(NHibernateMappingAttributesAssemblyName,
".HbmSerializer, ",
- NHibernateMappingAttributesAssemblyName));
+ NHibernateMappingAttributesAssemblyName))!;
var hbmSerializer = Activator.CreateInstance(hbmSerializerType);
- var validateProperty = hbmSerializerType.GetProperty("Validate");
- var serializeMethod = hbmSerializerType.GetMethod("Serialize", new[] { typeof(Assembly) });
+ var validateProperty = hbmSerializerType.GetProperty("Validate")!;
+ var serializeMethod = hbmSerializerType.GetMethod("Serialize", [typeof(Assembly)])!;
// Enable validation of mapping documents generated from the mapping attributes.
validateProperty.SetValue(hbmSerializer, true, null);
@@ -187,8 +190,9 @@ protected static void GenerateMappingFromAttributesIfNeeded(Configuration config
// Generates a stream of mapping documents from all decorated classes in targetAssembly
// and add it to NHibernate configuration.
configuration.AddInputStream(
- (MemoryStream) serializeMethod.Invoke(hbmSerializer,
- new object[] { Assembly.Load(targetAssemblyName) }));
+ (MemoryStream) serializeMethod.Invoke(
+ hbmSerializer,
+ new object[] { Assembly.Load(targetAssemblyName) })!);
}
}
@@ -200,7 +204,7 @@ private static Assembly LoadAssembly(string assemblyName)
}
catch (Exception ex)
{
- var message = string.Format("The assembly '{0}' could not be loaded.", assemblyName);
+ var message = $"The assembly '{assemblyName}' could not be loaded.";
throw new ConfigurationErrorsException(message, ex);
}
diff --git a/src/Castle.Facilities.NHibernateIntegration/Builders/PersistentConfigurationBuilder.cs b/src/Castle.Facilities.NHibernateIntegration/Builders/PersistentConfigurationBuilder.cs
index b8ad3d00a..74ead1ebf 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Builders/PersistentConfigurationBuilder.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Builders/PersistentConfigurationBuilder.cs
@@ -19,14 +19,12 @@ namespace Castle.Facilities.NHibernateIntegration.Builders
using System.Collections.Generic;
using System.Text.RegularExpressions;
+ using Castle.Core.Configuration;
using Castle.Core.Logging;
-
- using Core.Configuration;
+ using Castle.Facilities.NHibernateIntegration.Persisters;
using NHibernate.Cfg;
- using Persisters;
-
///
/// Serializes the for subsequent initializations.
///
@@ -103,7 +101,7 @@ private static string StripInvalidCharacters(string input)
return Regex.Replace(input, "[:*?\"<>\\\\/]", "", RegexOptions.IgnoreCase);
}
- private static IList GetDependentFilePathsFrom(IConfiguration facilityConfiguration)
+ private static List GetDependentFilePathsFrom(IConfiguration facilityConfiguration)
{
var list = new List();
diff --git a/src/Castle.Facilities.NHibernateIntegration/Builders/XmlConfigurationBuilder.cs b/src/Castle.Facilities.NHibernateIntegration/Builders/XmlConfigurationBuilder.cs
index c2557f083..b212f1f03 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Builders/XmlConfigurationBuilder.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Builders/XmlConfigurationBuilder.cs
@@ -18,9 +18,9 @@ namespace Castle.Facilities.NHibernateIntegration.Builders
{
using System.Xml;
- using Core.Configuration;
+ using Castle.Core.Configuration;
- using Internal;
+ using Castle.Facilities.NHibernateIntegration.Internal;
using NHibernate.Cfg;
@@ -38,7 +38,9 @@ public Configuration GetConfiguration(IConfiguration facilityConfiguration)
{
Configuration configuration;
- var configurationFile = facilityConfiguration.Attributes["nhibernateConfigFile"];
+ var configurationFile = facilityConfiguration.Attributes["nhibernateConfigFile"] ??
+ throw new ArgumentNullException(nameof(facilityConfiguration));
+
using (var configurationResource = new FileAssemblyResource(configurationFile))
{
using var reader = XmlReader.Create(configurationResource.GetStreamReader());
diff --git a/src/Castle.Facilities.NHibernateIntegration/Castle.Facilities.NHibernateIntegration.csproj b/src/Castle.Facilities.NHibernateIntegration/Castle.Facilities.NHibernateIntegration.csproj
index 26c74d299..ddd36fe9b 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Castle.Facilities.NHibernateIntegration.csproj
+++ b/src/Castle.Facilities.NHibernateIntegration/Castle.Facilities.NHibernateIntegration.csproj
@@ -17,12 +17,20 @@
-
-
-
-
-
-
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
diff --git a/src/Castle.Facilities.NHibernateIntegration/Components/Dao/DataException.cs b/src/Castle.Facilities.NHibernateIntegration/Components/Dao/DataException.cs
index a47028786..d844ff279 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Components/Dao/DataException.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Components/Dao/DataException.cs
@@ -17,7 +17,9 @@
namespace Castle.Facilities.NHibernateIntegration.Components.Dao
{
using System;
+#if NETFRAMEWORK
using System.Runtime.Serialization;
+#endif
///
/// Summary description for DataException.
diff --git a/src/Castle.Facilities.NHibernateIntegration/Components/Dao/IGenericDao.cs b/src/Castle.Facilities.NHibernateIntegration/Components/Dao/IGenericDao.cs
index fb559dc04..577ab8e4e 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Components/Dao/IGenericDao.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Components/Dao/IGenericDao.cs
@@ -31,7 +31,7 @@ public interface IGenericDao
///
/// The target type.
/// The of results
- Array FindAll(Type type);
+ Array? FindAll(Type type);
///
/// Returns a portion of the query results (sliced).
@@ -40,7 +40,7 @@ public interface IGenericDao
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
/// The of results
- Array FindAll(Type type, int firstRow, int maxRows);
+ Array? FindAll(Type type, int firstRow, int maxRows);
///
/// Finds an object instance by an unique ID.
@@ -48,7 +48,7 @@ public interface IGenericDao
/// The AR subclass type
/// ID value
/// The object instance.
- object FindById(Type type, object id);
+ object? FindById(Type type, object id);
///
/// Creates (Saves) a new instance to the database.
@@ -92,7 +92,7 @@ public interface IGenericDao
///
/// The target type.
/// The of results.
- Array FindAllStateless(Type type);
+ Array? FindAllStateless(Type type);
///
/// Returns a portion of the query results (sliced) using IStatelessSession.
@@ -101,7 +101,7 @@ public interface IGenericDao
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
/// The of results.
- Array FindAllStateless(Type type, int firstRow, int maxRows);
+ Array? FindAllStateless(Type type, int firstRow, int maxRows);
///
/// Finds an object instance by an unique ID using IStatelessSession.
@@ -109,14 +109,14 @@ public interface IGenericDao
/// The AR subclass type.
/// ID value.
/// The object instance.
- object FindByIdStateless(Type type, object id);
+ object? FindByIdStateless(Type type, object id);
///
/// Creates (saves or inserts) a new instance to the database using IStatelessSession.
///
/// The instance to be created on the database.
/// The instance.
- object CreateStateless(object instance);
+ object? CreateStateless(object instance);
///
/// Persists the modification on the instance state to the database using IStatelessSession.
diff --git a/src/Castle.Facilities.NHibernateIntegration/Components/Dao/INHibernateGenericDao.cs b/src/Castle.Facilities.NHibernateIntegration/Components/Dao/INHibernateGenericDao.cs
index b4cfba779..cdaafbb10 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Components/Dao/INHibernateGenericDao.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Components/Dao/INHibernateGenericDao.cs
@@ -20,6 +20,8 @@ namespace Castle.Facilities.NHibernateIntegration.Components.Dao
using NHibernate.Criterion;
+ using Array = System.Array;
+
///
/// Summary description for INHibernateGenericDao.
///
@@ -28,13 +30,26 @@ namespace Castle.Facilities.NHibernateIntegration.Components.Dao
///
public interface INHibernateGenericDao : IGenericDao
{
+ ///
+ /// Initializes the lazy properties.
+ ///
+ /// The instance.
+ void InitializeLazyProperties(object? instance);
+
+ ///
+ /// Initializes the lazy property.
+ ///
+ /// The instance.
+ /// Name of the property.
+ void InitializeLazyProperty(object? instance, string? propertyName);
+
///
/// Returns all instances found for the specified type using criteria.
///
/// The target type.
/// The criteria expression
/// The of results.
- Array FindAll(Type type, ICriterion[] criterias);
+ Array? FindAll(Type type, ICriterion[]? criterias);
///
/// Returns all instances found for the specified type using criteria.
@@ -44,7 +59,7 @@ public interface INHibernateGenericDao : IGenericDao
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
/// The of results.
- Array FindAll(Type type, ICriterion[] criterias, int firstRow, int maxRows);
+ Array? FindAll(Type type, ICriterion[]? criterias, int firstRow, int maxRows);
///
/// Returns all instances found for the specified type using criteria.
@@ -53,7 +68,7 @@ public interface INHibernateGenericDao : IGenericDao
/// The criteria expression
/// An of objects.
/// The of results.
- Array FindAll(Type type, ICriterion[] criterias, Order[] sortItems);
+ Array? FindAll(Type type, ICriterion[]? criterias, Order[]? sortItems);
///
/// Returns all instances found for the specified type using criteria.
@@ -64,14 +79,14 @@ public interface INHibernateGenericDao : IGenericDao
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
/// The of results.
- Array FindAll(Type type, ICriterion[] criterias, Order[] sortItems, int firstRow, int maxRows);
+ Array? FindAll(Type type, ICriterion[]? criterias, Order[]? sortItems, int firstRow, int maxRows);
///
/// Finds all with custom query.
///
/// The query string.
///
- Array FindAllWithCustomQuery(string queryString);
+ Array? FindAllWithCustomQuery(string? queryString);
///
/// Finds all with custom HQL query.
@@ -80,14 +95,14 @@ public interface INHibernateGenericDao : IGenericDao
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
///
- Array FindAllWithCustomQuery(string queryString, int firstRow, int maxRows);
+ Array? FindAllWithCustomQuery(string? queryString, int firstRow, int maxRows);
///
/// Finds all with named HQL query.
///
/// The named query.
///
- Array FindAllWithNamedQuery(string namedQuery);
+ Array? FindAllWithNamedQuery(string? namedQuery);
///
/// Finds all with named HQL query.
@@ -96,20 +111,7 @@ public interface INHibernateGenericDao : IGenericDao
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
///
- Array FindAllWithNamedQuery(string namedQuery, int firstRow, int maxRows);
-
- ///
- /// Initializes the lazy properties.
- ///
- /// The instance.
- void InitializeLazyProperties(object instance);
-
- ///
- /// Initializes the lazy property.
- ///
- /// The instance.
- /// Name of the property.
- void InitializeLazyProperty(object instance, string propertyName);
+ Array? FindAllWithNamedQuery(string? namedQuery, int firstRow, int maxRows);
///
/// Returns all instances found for the specified type
@@ -118,7 +120,7 @@ public interface INHibernateGenericDao : IGenericDao
/// The target type.
/// The criteria expression.
/// The of results.
- Array FindAllStateless(Type type, ICriterion[] criterias);
+ Array? FindAllStateless(Type type, ICriterion[]? criterias);
///
/// Returns all instances found for the specified type
@@ -129,7 +131,7 @@ public interface INHibernateGenericDao : IGenericDao
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
/// The of results.
- Array FindAllStateless(Type type, ICriterion[] criterias, int firstRow, int maxRows);
+ Array? FindAllStateless(Type type, ICriterion[]? criterias, int firstRow, int maxRows);
///
/// Returns all instances found for the specified type
@@ -139,7 +141,7 @@ public interface INHibernateGenericDao : IGenericDao
/// The criteria expression.
/// An of objects.
/// The of results.
- Array FindAllStateless(Type type, ICriterion[] criterias, Order[] sortItems);
+ Array? FindAllStateless(Type type, ICriterion[]? criterias, Order[]? sortItems);
///
/// Returns all instances found for the specified type
@@ -151,14 +153,14 @@ public interface INHibernateGenericDao : IGenericDao
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
/// The of results.
- Array FindAllStateless(Type type, ICriterion[] criterias, Order[] sortItems, int firstRow, int maxRows);
+ Array? FindAllStateless(Type type, ICriterion[]? criterias, Order[]? sortItems, int firstRow, int maxRows);
///
/// Finds all with custom query using IStatelessSession.
///
/// The query string.
///
- Array FindAllWithCustomQueryStateless(string queryString);
+ Array? FindAllWithCustomQueryStateless(string? queryString);
///
/// Finds all with custom HQL query using IStatelessSession.
@@ -167,14 +169,14 @@ public interface INHibernateGenericDao : IGenericDao
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
///
- Array FindAllWithCustomQueryStateless(string queryString, int firstRow, int maxRows);
+ Array? FindAllWithCustomQueryStateless(string? queryString, int firstRow, int maxRows);
///
/// Finds all with named HQL query using IStatelessSession.
///
/// The named query.
///
- Array FindAllWithNamedQueryStateless(string namedQuery);
+ Array? FindAllWithNamedQueryStateless(string? namedQuery);
///
/// Finds all with named HQL query using IStatelessSession.
@@ -183,6 +185,6 @@ public interface INHibernateGenericDao : IGenericDao
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
///
- Array FindAllWithNamedQueryStateless(string namedQuery, int firstRow, int maxRows);
+ Array? FindAllWithNamedQueryStateless(string? namedQuery, int firstRow, int maxRows);
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration/Components/Dao/NHibernateGenericDao.cs b/src/Castle.Facilities.NHibernateIntegration/Components/Dao/NHibernateGenericDao.cs
index 16d2b764a..ac8c6e7d6 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Components/Dao/NHibernateGenericDao.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Components/Dao/NHibernateGenericDao.cs
@@ -18,13 +18,13 @@ namespace Castle.Facilities.NHibernateIntegration.Components.Dao
{
using System;
+ using Castle.Facilities.NHibernateIntegration.Util;
+
using NHibernate;
using NHibernate.Collection;
using NHibernate.Criterion;
using NHibernate.Proxy;
- using Util;
-
///
/// Summary description for GenericDao.
///
@@ -47,7 +47,7 @@ public NHibernateGenericDao(ISessionManager sessionManager)
///
/// The session manager.
/// The session factory alias.
- public NHibernateGenericDao(ISessionManager sessionManager, string sessionFactoryAlias) :
+ public NHibernateGenericDao(ISessionManager sessionManager, string? sessionFactoryAlias) :
this(sessionManager)
{
SessionFactoryAlias = sessionFactoryAlias;
@@ -63,16 +63,80 @@ public NHibernateGenericDao(ISessionManager sessionManager, string sessionFactor
/// Gets or sets the session factory alias.
///
/// The session factory alias.
- public string SessionFactoryAlias { get; set; } = null;
+ public string? SessionFactoryAlias { get; set; } = null;
#region IGenericDAO Members
+ ///
+ /// Initializes the lazy properties.
+ ///
+ /// The instance.
+ public void InitializeLazyProperties(object? instance)
+ {
+ if (instance == null)
+ {
+ throw new ArgumentNullException(nameof(instance));
+ }
+
+ using var session = GetSession();
+
+ foreach (var value in ReflectionUtility.GetPropertiesDictionary(instance).Values)
+ {
+ if (value is INHibernateProxy or IPersistentCollection)
+ {
+ if (!NHibernateUtil.IsInitialized(value))
+ {
+ session.Lock(instance, LockMode.None);
+ NHibernateUtil.Initialize(value);
+ }
+ }
+ }
+ }
+
+ ///
+ /// Initializes the lazy property.
+ ///
+ /// The instance.
+ /// The name of the property.
+ public void InitializeLazyProperty(object? instance, string? propertyName)
+ {
+ if (instance == null)
+ {
+ throw new ArgumentNullException(nameof(instance));
+ }
+
+ if (string.IsNullOrEmpty(propertyName))
+ {
+ throw new ArgumentNullException(nameof(propertyName));
+ }
+
+ var properties = ReflectionUtility.GetPropertiesDictionary(instance);
+ if (!properties.ContainsKey(propertyName!))
+ {
+ throw new ArgumentOutOfRangeException(nameof(propertyName),
+ $"Property {propertyName} doest not exist for type {instance.GetType()}.");
+ }
+
+ using var session = GetSession();
+
+ var value = properties[propertyName!];
+
+ if (value is INHibernateProxy or IPersistentCollection)
+ {
+ if (!NHibernateUtil.IsInitialized(value))
+ {
+ session.Lock(instance, LockMode.None);
+ NHibernateUtil.Initialize(value);
+ }
+ }
+ }
+
///
/// Returns all instances found for the specified type.
///
/// The target type.
/// The of results
- public virtual Array FindAll(Type type)
+ public virtual Array? FindAll(Type type)
{
return FindAll(type, int.MinValue, int.MinValue);
}
@@ -84,9 +148,10 @@ public virtual Array FindAll(Type type)
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
/// The of results.
- public virtual Array FindAll(Type type, int firstRow, int maxRows)
+ public virtual Array? FindAll(Type type, int firstRow, int maxRows)
{
using var session = GetSession();
+
try
{
var criteria = session.CreateCriteria(type);
@@ -110,7 +175,7 @@ public virtual Array FindAll(Type type, int firstRow, int maxRows)
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(FindAll)} for {type.Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(FindAll), type), ex);
}
}
@@ -123,6 +188,7 @@ public virtual Array FindAll(Type type, int firstRow, int maxRows)
public virtual object FindById(Type type, object id)
{
using var session = GetSession();
+
try
{
return session.Load(type, id);
@@ -133,7 +199,7 @@ public virtual object FindById(Type type, object id)
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(FindById)} for {type.Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(FindById), type), ex);
}
}
@@ -145,13 +211,14 @@ public virtual object FindById(Type type, object id)
public virtual object Create(object instance)
{
using var session = GetSession();
+
try
{
return session.Save(instance);
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(Create)} for {instance.GetType().Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(Create), instance.GetType()), ex);
}
}
@@ -162,13 +229,14 @@ public virtual object Create(object instance)
public virtual void Update(object instance)
{
using var session = GetSession();
+
try
{
session.Update(instance);
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(Update)} for {instance.GetType().Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(Update), instance.GetType()), ex);
}
}
@@ -179,13 +247,14 @@ public virtual void Update(object instance)
public virtual void Delete(object instance)
{
using var session = GetSession();
+
try
{
session.Delete(instance);
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(Delete)} for {instance.GetType().Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(Delete), instance.GetType()), ex);
}
}
@@ -196,13 +265,14 @@ public virtual void Delete(object instance)
public virtual void DeleteAll(Type type)
{
using var session = GetSession();
+
try
{
- session.Delete(string.Format("from {0}", type.Name));
+ session.Delete($"from {type.Name}");
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(DeleteAll)} for {type.Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(DeleteAll), type), ex);
}
}
@@ -219,13 +289,14 @@ public virtual void DeleteAll(Type type)
public virtual void Save(object instance)
{
using var session = GetSession();
+
try
{
session.SaveOrUpdate(instance);
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(Save)} for {instance.GetType().Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(Save), instance.GetType()), ex);
}
}
@@ -249,6 +320,7 @@ public virtual Array FindAllStateless(Type type)
public virtual Array FindAllStateless(Type type, int firstRow, int maxRows)
{
using var session = GetStatelessSession();
+
try
{
var criteria = session.CreateCriteria(type);
@@ -272,7 +344,7 @@ public virtual Array FindAllStateless(Type type, int firstRow, int maxRows)
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(FindAllStateless)} for {type.Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(FindAllStateless), type), ex);
}
}
@@ -285,6 +357,7 @@ public virtual Array FindAllStateless(Type type, int firstRow, int maxRows)
public object FindByIdStateless(Type type, object id)
{
using var session = GetStatelessSession();
+
try
{
return session.Get(type.FullName, id);
@@ -295,7 +368,7 @@ public object FindByIdStateless(Type type, object id)
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(FindByIdStateless)} for {type.Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(FindByIdStateless), type), ex);
}
}
@@ -307,13 +380,14 @@ public object FindByIdStateless(Type type, object id)
public object CreateStateless(object instance)
{
using var session = GetStatelessSession();
+
try
{
return session.Insert(instance);
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(CreateStateless)} for {instance.GetType().Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(CreateStateless), instance.GetType()), ex);
}
}
@@ -324,13 +398,14 @@ public object CreateStateless(object instance)
public void UpdateStateless(object instance)
{
using var session = GetStatelessSession();
+
try
{
session.Update(instance);
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(UpdateStateless)} for {instance.GetType().Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(UpdateStateless), instance.GetType()), ex);
}
}
@@ -341,13 +416,14 @@ public void UpdateStateless(object instance)
public void DeleteStateless(object instance)
{
using var session = GetStatelessSession();
+
try
{
session.Delete(instance);
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(DeleteStateless)} for {instance.GetType().Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(DeleteStateless), instance.GetType()), ex);
}
}
@@ -358,13 +434,14 @@ public void DeleteStateless(object instance)
public void DeleteAllStateless(Type type)
{
using var session = GetStatelessSession();
+
try
{
session.Delete($"from {type.Name}");
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(DeleteAllStateless)} for {type.Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(DeleteAllStateless), type), ex);
}
}
@@ -378,7 +455,7 @@ public void DeleteAllStateless(Type type)
/// The target type.
/// The criteria expression.
/// The of results.
- public virtual Array FindAll(Type type, ICriterion[] criterias)
+ public virtual Array? FindAll(Type type, ICriterion[]? criterias)
{
return FindAll(type, criterias, null, int.MinValue, int.MinValue);
}
@@ -391,7 +468,7 @@ public virtual Array FindAll(Type type, ICriterion[] criterias)
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
/// The of results.
- public virtual Array FindAll(Type type, ICriterion[] criterias, int firstRow, int maxRows)
+ public virtual Array? FindAll(Type type, ICriterion[]? criterias, int firstRow, int maxRows)
{
return FindAll(type, criterias, null, firstRow, maxRows);
}
@@ -403,7 +480,7 @@ public virtual Array FindAll(Type type, ICriterion[] criterias, int firstRow, in
/// The criteria expression.
/// An of objects.
/// The of results.
- public virtual Array FindAll(Type type, ICriterion[] criterias, Order[] sortItems)
+ public virtual Array? FindAll(Type type, ICriterion[]? criterias, Order[]? sortItems)
{
return FindAll(type, criterias, sortItems, int.MinValue, int.MinValue);
}
@@ -417,9 +494,10 @@ public virtual Array FindAll(Type type, ICriterion[] criterias, Order[] sortItem
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
/// The of results.
- public virtual Array FindAll(Type type, ICriterion[] criterias, Order[] sortItems, int firstRow, int maxRows)
+ public virtual Array? FindAll(Type type, ICriterion[]? criterias, Order[]? sortItems, int firstRow, int maxRows)
{
using var session = GetSession();
+
try
{
var criteria = session.CreateCriteria(type);
@@ -459,7 +537,7 @@ public virtual Array FindAll(Type type, ICriterion[] criterias, Order[] sortItem
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(FindAll)} for {type.Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(FindAll), type), ex);
}
}
@@ -468,7 +546,7 @@ public virtual Array FindAll(Type type, ICriterion[] criterias, Order[] sortItem
///
/// The query string.
///
- public virtual Array FindAllWithCustomQuery(string queryString)
+ public virtual Array? FindAllWithCustomQuery(string? queryString)
{
return FindAllWithCustomQuery(queryString, int.MinValue, int.MinValue);
}
@@ -480,7 +558,7 @@ public virtual Array FindAllWithCustomQuery(string queryString)
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
///
- public virtual Array FindAllWithCustomQuery(string queryString, int firstRow, int maxRows)
+ public virtual Array? FindAllWithCustomQuery(string? queryString, int firstRow, int maxRows)
{
if (string.IsNullOrEmpty(queryString))
{
@@ -488,6 +566,7 @@ public virtual Array FindAllWithCustomQuery(string queryString, int firstRow, in
}
using var session = GetSession();
+
try
{
var query = session.CreateQuery(queryString);
@@ -508,14 +587,14 @@ public virtual Array FindAllWithCustomQuery(string queryString, int firstRow, in
return null;
}
- var array = Array.CreateInstance(result[0].GetType(), result.Count);
+ var array = Array.CreateInstance(result[0]!.GetType(), result.Count);
result.CopyTo(array, 0);
return array;
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(FindAllWithCustomQuery)}: {queryString}", ex);
+ throw new DataException(GetMessageForQuery(nameof(FindAllWithCustomQuery), queryString!), ex);
}
}
@@ -524,7 +603,7 @@ public virtual Array FindAllWithCustomQuery(string queryString, int firstRow, in
///
/// The named query.
///
- public virtual Array FindAllWithNamedQuery(string namedQuery)
+ public virtual Array? FindAllWithNamedQuery(string? namedQuery)
{
return FindAllWithNamedQuery(namedQuery, int.MinValue, int.MinValue);
}
@@ -536,7 +615,7 @@ public virtual Array FindAllWithNamedQuery(string namedQuery)
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
///
- public virtual Array FindAllWithNamedQuery(string namedQuery, int firstRow, int maxRows)
+ public virtual Array? FindAllWithNamedQuery(string? namedQuery, int firstRow, int maxRows)
{
if (string.IsNullOrEmpty(namedQuery))
{
@@ -544,6 +623,7 @@ public virtual Array FindAllWithNamedQuery(string namedQuery, int firstRow, int
}
using var session = GetSession();
+
try
{
var query = session.GetNamedQuery(namedQuery);
@@ -568,76 +648,14 @@ public virtual Array FindAllWithNamedQuery(string namedQuery, int firstRow, int
return null;
}
- var array = Array.CreateInstance(result[0].GetType(), result.Count);
+ var array = Array.CreateInstance(result[0]!.GetType(), result.Count);
result.CopyTo(array, 0);
return array;
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(FindAllWithNamedQuery)}: {namedQuery}", ex);
- }
- }
-
- ///
- /// Initializes the lazy properties.
- ///
- /// The instance.
- public void InitializeLazyProperties(object instance)
- {
- if (instance == null)
- {
- throw new ArgumentNullException(nameof(instance));
- }
-
- using var session = GetSession();
- foreach (var value in ReflectionUtility.GetPropertiesDictionary(instance).Values)
- {
- if (value is INHibernateProxy or IPersistentCollection)
- {
- if (!NHibernateUtil.IsInitialized(value))
- {
- session.Lock(instance, LockMode.None);
- NHibernateUtil.Initialize(value);
- }
- }
- }
- }
-
- ///
- /// Initializes the lazy property.
- ///
- /// The instance.
- /// The name of the property.
- public void InitializeLazyProperty(object instance, string propertyName)
- {
- if (instance == null)
- {
- throw new ArgumentNullException(nameof(instance));
- }
-
- if (string.IsNullOrEmpty(propertyName))
- {
- throw new ArgumentNullException(nameof(propertyName));
- }
-
- var properties = ReflectionUtility.GetPropertiesDictionary(instance);
- if (!properties.ContainsKey(propertyName))
- {
- throw new ArgumentOutOfRangeException(nameof(propertyName),
- $"Property {propertyName} doest not exist for type {instance.GetType()}.");
- }
-
- using var session = GetSession();
- var value = properties[propertyName];
-
- if (value is INHibernateProxy or IPersistentCollection)
- {
- if (!NHibernateUtil.IsInitialized(value))
- {
- session.Lock(instance, LockMode.None);
- NHibernateUtil.Initialize(value);
- }
+ throw new DataException(GetMessageForQuery(nameof(FindAllWithNamedQuery), namedQuery!), ex);
}
}
@@ -648,7 +666,7 @@ public void InitializeLazyProperty(object instance, string propertyName)
/// The target type.
/// The criteria expression.
/// The of results.
- public virtual Array FindAllStateless(Type type, ICriterion[] criterias)
+ public virtual Array? FindAllStateless(Type type, ICriterion[]? criterias)
{
return FindAllStateless(type, criterias, null, int.MinValue, int.MinValue);
}
@@ -662,7 +680,7 @@ public virtual Array FindAllStateless(Type type, ICriterion[] criterias)
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
/// The of results.
- public virtual Array FindAllStateless(Type type, ICriterion[] criterias, int firstRow, int maxRows)
+ public virtual Array? FindAllStateless(Type type, ICriterion[]? criterias, int firstRow, int maxRows)
{
return FindAllStateless(type, criterias, null, firstRow, maxRows);
}
@@ -675,7 +693,7 @@ public virtual Array FindAllStateless(Type type, ICriterion[] criterias, int fir
/// The criteria expression.
/// An of objects.
/// The of results.
- public virtual Array FindAllStateless(Type type, ICriterion[] criterias, Order[] sortItems)
+ public virtual Array FindAllStateless(Type type, ICriterion[]? criterias, Order[]? sortItems)
{
return FindAllStateless(type, criterias, sortItems, int.MinValue, int.MinValue);
}
@@ -690,9 +708,10 @@ public virtual Array FindAllStateless(Type type, ICriterion[] criterias, Order[]
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
/// The of results.
- public virtual Array FindAllStateless(Type type, ICriterion[] criterias, Order[] sortItems, int firstRow, int maxRows)
+ public virtual Array FindAllStateless(Type type, ICriterion[]? criterias, Order[]? sortItems, int firstRow, int maxRows)
{
using var session = GetStatelessSession();
+
try
{
var criteria = session.CreateCriteria(type);
@@ -732,7 +751,7 @@ public virtual Array FindAllStateless(Type type, ICriterion[] criterias, Order[]
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(FindAllStateless)} for {type.Name}.", ex);
+ throw new DataException(GetMessageForType(nameof(FindAllStateless), type), ex);
}
}
@@ -741,7 +760,7 @@ public virtual Array FindAllStateless(Type type, ICriterion[] criterias, Order[]
///
/// The query string.
///
- public virtual Array FindAllWithCustomQueryStateless(string queryString)
+ public virtual Array? FindAllWithCustomQueryStateless(string? queryString)
{
return FindAllWithCustomQueryStateless(queryString, int.MinValue, int.MinValue);
}
@@ -753,7 +772,7 @@ public virtual Array FindAllWithCustomQueryStateless(string queryString)
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
///
- public virtual Array FindAllWithCustomQueryStateless(string queryString, int firstRow, int maxRows)
+ public virtual Array? FindAllWithCustomQueryStateless(string? queryString, int firstRow, int maxRows)
{
if (string.IsNullOrEmpty(queryString))
{
@@ -761,6 +780,7 @@ public virtual Array FindAllWithCustomQueryStateless(string queryString, int fir
}
using var session = GetStatelessSession();
+
try
{
var query = session.CreateQuery(queryString);
@@ -781,14 +801,14 @@ public virtual Array FindAllWithCustomQueryStateless(string queryString, int fir
return null;
}
- var array = Array.CreateInstance(result[0].GetType(), result.Count);
+ var array = Array.CreateInstance(result[0]!.GetType(), result.Count);
result.CopyTo(array, 0);
return array;
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(FindAllWithCustomQueryStateless)}: {queryString}", ex);
+ throw new DataException(GetMessageForQuery(nameof(FindAllWithCustomQueryStateless), queryString!), ex);
}
}
@@ -797,7 +817,7 @@ public virtual Array FindAllWithCustomQueryStateless(string queryString, int fir
///
/// The named query.
///
- public virtual Array FindAllWithNamedQueryStateless(string namedQuery)
+ public virtual Array? FindAllWithNamedQueryStateless(string? namedQuery)
{
return FindAllWithNamedQueryStateless(namedQuery, int.MinValue, int.MinValue);
}
@@ -809,7 +829,7 @@ public virtual Array FindAllWithNamedQueryStateless(string namedQuery)
/// The number of the first row to retrieve.
/// The maximum number of results retrieved.
///
- public virtual Array FindAllWithNamedQueryStateless(string namedQuery, int firstRow, int maxRows)
+ public virtual Array? FindAllWithNamedQueryStateless(string? namedQuery, int firstRow, int maxRows)
{
if (string.IsNullOrEmpty(namedQuery))
{
@@ -817,6 +837,7 @@ public virtual Array FindAllWithNamedQueryStateless(string namedQuery, int first
}
using var session = GetStatelessSession();
+
try
{
var query = session.GetNamedQuery(namedQuery);
@@ -841,17 +862,27 @@ public virtual Array FindAllWithNamedQueryStateless(string namedQuery, int first
return null;
}
- var array = Array.CreateInstance(result[0].GetType(), result.Count);
+ var array = Array.CreateInstance(result[0]!.GetType(), result.Count);
result.CopyTo(array, 0);
return array;
}
catch (Exception ex)
{
- throw new DataException($"Could not perform {nameof(FindAllWithNamedQueryStateless)}: {namedQuery}", ex);
+ throw new DataException(GetMessageForQuery(nameof(FindAllWithNamedQueryStateless), namedQuery!), ex);
}
}
+ private static string GetMessageForType(string methodName, Type type)
+ {
+ return $"Could not perform '{methodName}()' for '{type.Name}'.";
+ }
+
+ private static string GetMessageForQuery(string methodName, string query)
+ {
+ return $"Could not perform '{methodName}()': {query}";
+ }
+
#endregion
private ISession GetSession()
diff --git a/src/Castle.Facilities.NHibernateIntegration/Components/Web/SessionWebModule.cs b/src/Castle.Facilities.NHibernateIntegration/Components/Web/SessionWebModule.cs
index a41e6f3e2..cb122bdd7 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Components/Web/SessionWebModule.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Components/Web/SessionWebModule.cs
@@ -14,18 +14,17 @@
// limitations under the License.
#endregion
+#if NETFRAMEWORK
namespace Castle.Facilities.NHibernateIntegration.Components.Web
{
-#if NETFRAMEWORK
using System;
using System.Web;
- using MicroKernel.Facilities;
+ using Castle.MicroKernel.Facilities;
+ using Castle.Windsor;
using NHibernate;
- using Windsor;
-
///
/// HttpModule to set up a session for the request lifetime.
///
@@ -94,8 +93,8 @@ private static IWindsorContainer ObtainContainer()
{
if (HttpContext.Current.ApplicationInstance is not IContainerAccessor containerAccessor)
{
- throw new FacilityException("You must extend the HttpApplication in your web project " +
- "and implement the IContainerAccessor to properly expose your container instance.");
+ throw new FacilityException($"You must extend the '{nameof(HttpApplication)}' in your web project " +
+ $"and implement the '{nameof(IContainerAccessor)}' to properly expose your container instance.");
}
var container = containerAccessor.Container;
@@ -103,11 +102,11 @@ private static IWindsorContainer ObtainContainer()
if (container == null)
{
throw new FacilityException("The container seems to be unavailable (null) " +
- "in your HttpApplication subclass.");
+ $"in your '{nameof(HttpApplication)}' subclass.");
}
return container;
}
}
-#endif
}
+#endif
diff --git a/src/Castle.Facilities.NHibernateIntegration/DefaultSessionManager.cs b/src/Castle.Facilities.NHibernateIntegration/DefaultSessionManager.cs
index ef982f675..1db9ab89a 100644
--- a/src/Castle.Facilities.NHibernateIntegration/DefaultSessionManager.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/DefaultSessionManager.cs
@@ -21,13 +21,14 @@ namespace Castle.Facilities.NHibernateIntegration
using System.Data;
using Castle.Facilities.NHibernateIntegration.Internal;
+ using Castle.Facilities.NHibernateIntegration.Util;
using Castle.MicroKernel;
using Castle.MicroKernel.Facilities;
using Castle.Services.Transaction;
using NHibernate;
- using ITransaction = Services.Transaction.ITransaction;
+ using ITransaction = Castle.Services.Transaction.ITransaction;
///
/// Default session manager implementation.
@@ -42,7 +43,10 @@ public class DefaultSessionManager : MarshalByRefObject, ISessionManager
///
/// Format string for component key.
///
- public const string InterceptorKeyFormatString = "nhibernate.session.interceptor.{0}";
+ public const string InterceptorKeyFormat = "nhibernate.session.interceptor.{0}";
+
+ internal const string SessionEnlistedContextKey = "nh.session.enlisted";
+ internal const string StatelessSessionEnlistedContextKey = "nh.statelessSession.enlisted";
private readonly IKernel _kernel;
private readonly ISessionStore _sessionStore;
@@ -54,10 +58,9 @@ public class DefaultSessionManager : MarshalByRefObject, ISessionManager
/// The .
/// The .
/// The .
- public DefaultSessionManager(
- IKernel kernel,
- ISessionStore sessionStore,
- ISessionFactoryResolver sessionFactoryResolver)
+ public DefaultSessionManager(IKernel kernel,
+ ISessionStore sessionStore,
+ ISessionFactoryResolver sessionFactoryResolver)
{
_kernel = kernel;
_sessionStore = sessionStore;
@@ -84,7 +87,7 @@ public ISession OpenSession()
///
///
///
- public ISession OpenSession(string alias)
+ public ISession OpenSession(string? alias)
{
if (alias == null)
{
@@ -93,23 +96,22 @@ public ISession OpenSession(string alias)
var transaction = GetCurrentTransaction();
- var wrapped = _sessionStore.FindCompatibleSession(alias);
-
- if (wrapped == null)
+ var wrappedSession = _sessionStore.FindCompatibleSession(alias);
+ if (wrappedSession == null)
{
var session = CreateSession(alias);
- wrapped = WrapSession(transaction != null, session);
- EnlistIfNecessary(true, transaction, wrapped);
- _sessionStore.Store(alias, wrapped);
+ wrappedSession = WrapSession(transaction != null, session);
+ EnlistIfNecessary(true, transaction, wrappedSession);
+ _sessionStore.Store(alias, wrappedSession);
}
else
{
- EnlistIfNecessary(false, transaction, wrapped);
- wrapped = WrapSession(true, wrapped.InnerSession);
+ EnlistIfNecessary(false, transaction, wrappedSession);
+ wrappedSession = WrapSession(true, wrappedSession.InnerSession);
}
- return wrapped;
+ return wrappedSession;
}
///
@@ -126,7 +128,7 @@ public IStatelessSession OpenStatelessSession()
///
///
///
- public IStatelessSession OpenStatelessSession(string alias)
+ public IStatelessSession OpenStatelessSession(string? alias)
{
if (alias == null)
{
@@ -135,23 +137,22 @@ public IStatelessSession OpenStatelessSession(string alias)
var transaction = GetCurrentTransaction();
- var wrapped = _sessionStore.FindCompatibleStatelessSession(alias);
-
- if (wrapped == null)
+ var wrappedSession = _sessionStore.FindCompatibleStatelessSession(alias);
+ if (wrappedSession == null)
{
var session = CreateStatelessSession(alias);
- wrapped = WrapStatelessSession(transaction != null, session);
- EnlistIfNecessary(true, transaction, wrapped);
- _sessionStore.Store(alias, wrapped);
+ wrappedSession = WrapStatelessSession(transaction != null, session);
+ EnlistIfNecessary(true, transaction, wrappedSession);
+ _sessionStore.Store(alias, wrappedSession);
}
else
{
- EnlistIfNecessary(false, transaction, wrapped);
- wrapped = WrapStatelessSession(true, wrapped.InnerSession);
+ EnlistIfNecessary(false, transaction, wrappedSession);
+ wrappedSession = WrapStatelessSession(true, wrappedSession.InnerSession);
}
- return wrapped;
+ return wrappedSession;
}
///
@@ -161,20 +162,19 @@ public IStatelessSession OpenStatelessSession(string alias)
/// The transaction.
/// The session.
///
- protected static bool EnlistIfNecessary(
- bool weAreSessionOwner,
- ITransaction transaction,
- SessionDelegate session)
+ protected static bool EnlistIfNecessary(bool weAreSessionOwner,
+ ITransaction? transaction,
+ SessionDelegate session)
{
if (transaction == null)
{
return false;
}
- var list = (IList) transaction.Context["nh.session.enlisted"];
-
bool shouldEnlist;
+ transaction.Context.TryGetValueAs(SessionEnlistedContextKey,
+ out IList? list);
if (list == null)
{
list = new List();
@@ -198,9 +198,11 @@ protected static bool EnlistIfNecessary(
if (shouldEnlist)
{
- if (session.Transaction == null || !session.Transaction.IsActive)
+ //var currentTransaction = session.Transaction;
+ var currentTransaction = session.GetCurrentTransaction();
+ if (currentTransaction == null || !currentTransaction.IsActive)
{
- transaction.Context["nh.session.enlisted"] = list;
+ transaction.Context[SessionEnlistedContextKey] = list;
var level = TranslateTransactionIsolationLevel(transaction.IsolationLevel);
transaction.Enlist(new ResourceAdapter(session.BeginTransaction(level), transaction.IsAmbient));
@@ -224,20 +226,19 @@ protected static bool EnlistIfNecessary(
/// The transaction.
/// The stateless session.
///
- protected static bool EnlistIfNecessary(
- bool weAreSessionOwner,
- ITransaction transaction,
- StatelessSessionDelegate statelessSession)
+ protected static bool EnlistIfNecessary(bool weAreSessionOwner,
+ ITransaction? transaction,
+ StatelessSessionDelegate statelessSession)
{
if (transaction == null)
{
return false;
}
- var list = (IList) transaction.Context["nh.statelessSession.enlisted"];
-
bool shouldEnlist;
+ transaction.Context.TryGetValueAs(StatelessSessionEnlistedContextKey,
+ out IList? list);
if (list == null)
{
list = new List();
@@ -261,9 +262,11 @@ protected static bool EnlistIfNecessary(
if (shouldEnlist)
{
- if (statelessSession.Transaction == null || !statelessSession.Transaction.IsActive)
+ //var currentTransaction = statelessSession.Transaction;
+ var currentTransaction = statelessSession.GetCurrentTransaction();
+ if (currentTransaction == null || !currentTransaction.IsActive)
{
- transaction.Context["nh.statelessSession.enlisted"] = list;
+ transaction.Context[StatelessSessionEnlistedContextKey] = list;
var level = TranslateTransactionIsolationLevel(transaction.IsolationLevel);
transaction.Enlist(new ResourceAdapter(statelessSession.BeginTransaction(level), transaction.IsAmbient));
@@ -295,7 +298,7 @@ private static IsolationLevel TranslateTransactionIsolationLevel(
};
}
- private ITransaction GetCurrentTransaction()
+ private ITransaction? GetCurrentTransaction()
{
var transactionManager = _kernel.Resolve();
return transactionManager.CurrentTransaction;
@@ -317,13 +320,14 @@ private ISession CreateSession(string alias)
if (sessionFactory == null)
{
- throw new FacilityException($"No {nameof(ISessionFactory)} implementation " +
- $"associated with the given {nameof(ISession)} alias: {alias}.");
+ throw new FacilityException(
+ $"No '{nameof(ISessionFactory)}' implementation " +
+ $"associated with the given '{nameof(ISession)}' alias: '{alias}'.");
}
ISession session;
- var aliasedInterceptorId = string.Format(InterceptorKeyFormatString, alias);
+ var aliasedInterceptorId = string.Format(InterceptorKeyFormat, alias);
if (_kernel.HasComponent(aliasedInterceptorId))
{
@@ -357,8 +361,9 @@ private IStatelessSession CreateStatelessSession(string alias)
if (sessionFactory == null)
{
- throw new FacilityException($"No {nameof(ISessionFactory)} implementation " +
- $"associated with the given {nameof(IStatelessSession)} alias: {alias}.");
+ throw new FacilityException(
+ $"No '{nameof(ISessionFactory)}' implementation " +
+ $"associated with the given '{nameof(IStatelessSession)}' alias: '{alias}'.");
}
var session = sessionFactory.OpenStatelessSession();
diff --git a/src/Castle.Facilities.NHibernateIntegration/IConfigurationBuilder.cs b/src/Castle.Facilities.NHibernateIntegration/IConfigurationBuilder.cs
index bc846fbce..dce51c995 100644
--- a/src/Castle.Facilities.NHibernateIntegration/IConfigurationBuilder.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/IConfigurationBuilder.cs
@@ -16,7 +16,7 @@
namespace Castle.Facilities.NHibernateIntegration
{
- using Core.Configuration;
+ using Castle.Core.Configuration;
using NHibernate.Cfg;
diff --git a/src/Castle.Facilities.NHibernateIntegration/ISessionFactoryResolver.cs b/src/Castle.Facilities.NHibernateIntegration/ISessionFactoryResolver.cs
index 4e60c765f..d4dcbf148 100644
--- a/src/Castle.Facilities.NHibernateIntegration/ISessionFactoryResolver.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/ISessionFactoryResolver.cs
@@ -16,7 +16,7 @@
namespace Castle.Facilities.NHibernateIntegration
{
- using MicroKernel.Facilities;
+ using Castle.MicroKernel.Facilities;
using NHibernate;
diff --git a/src/Castle.Facilities.NHibernateIntegration/ISessionManager.cs b/src/Castle.Facilities.NHibernateIntegration/ISessionManager.cs
index def931f58..7e56a3ad2 100644
--- a/src/Castle.Facilities.NHibernateIntegration/ISessionManager.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/ISessionManager.cs
@@ -41,7 +41,7 @@ public interface ISessionManager
///
///
///
- ISession OpenSession(string alias);
+ ISession OpenSession(string? alias);
///
/// Returns a valid opened and connected instance.
@@ -54,6 +54,6 @@ public interface ISessionManager
///
///
///
- IStatelessSession OpenStatelessSession(string alias);
+ IStatelessSession OpenStatelessSession(string? alias);
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration/ISessionStore.cs b/src/Castle.Facilities.NHibernateIntegration/ISessionStore.cs
index 3d3421320..f5311211f 100644
--- a/src/Castle.Facilities.NHibernateIntegration/ISessionStore.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/ISessionStore.cs
@@ -26,7 +26,7 @@ public interface ISessionStore
/// Returns true if the current activity
/// (which is an execution activity context) has no sessions available.
///
- bool IsCurrentActivityEmptyFor(string alias);
+ bool IsCurrentActivityEmptyFor(string? alias);
///
/// Should return a previously stored session for the given alias if available,
@@ -34,7 +34,7 @@ public interface ISessionStore
///
///
///
- SessionDelegate FindCompatibleSession(string alias);
+ SessionDelegate? FindCompatibleSession(string? alias);
///
/// Should store the specified session instance.
@@ -55,7 +55,7 @@ public interface ISessionStore
///
///
///
- StatelessSessionDelegate FindCompatibleStatelessSession(string alias);
+ StatelessSessionDelegate? FindCompatibleStatelessSession(string? alias);
///
/// Should store the specified stateless session instance.
diff --git a/src/Castle.Facilities.NHibernateIntegration/Internal/NHibernateSessionInterceptor.cs b/src/Castle.Facilities.NHibernateIntegration/Internal/NHibernateSessionInterceptor.cs
index 2df9ebce7..16bdcffb3 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Internal/NHibernateSessionInterceptor.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Internal/NHibernateSessionInterceptor.cs
@@ -32,7 +32,7 @@ namespace Castle.Facilities.NHibernateIntegration.Internal
public class NHibernateSessionInterceptor : IInterceptor, IOnBehalfAware
{
private readonly ISessionManager _sessionManager;
- private IEnumerable _metaInfo;
+ private IEnumerable? _metaInfo;
///
/// Constructor.
@@ -58,7 +58,7 @@ public void Intercept(IInvocation invocation)
{
MethodInfo methodInfo;
- if (invocation.Method.DeclaringType.IsInterface)
+ if (invocation.Method.DeclaringType!.IsInterface)
{
methodInfo = invocation.MethodInvocationTarget;
}
diff --git a/src/Castle.Facilities.NHibernateIntegration/Internal/SessionDelegate.cs b/src/Castle.Facilities.NHibernateIntegration/Internal/SessionDelegate.cs
index 35d986ab2..889748a3a 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Internal/SessionDelegate.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Internal/SessionDelegate.cs
@@ -35,20 +35,14 @@ namespace Castle.Facilities.NHibernateIntegration
///
///
///
- ///
- /// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0618
- ///
- /// #pragma warning disable 0618, 0612
- /// #pragma warning restore 0618, 0612
- ///
- ///
[Serializable]
public class SessionDelegate : MarshalByRefObject, ISession
{
- private readonly bool _canClose;
private readonly ISessionStore _sessionStore;
- private object _cookie;
+ private readonly bool _canClose;
+
private bool _disposed;
+ private object? _cookie;
///
/// Initializes a new instance of the class.
@@ -56,13 +50,6 @@ public class SessionDelegate : MarshalByRefObject, ISession
/// The inner session.
/// The session store.
/// Set to true if can close the session.
- ///
- /// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0618
- ///
- /// #pragma warning disable 0618, 0612
- /// #pragma warning restore 0618, 0612
- ///
- ///
public SessionDelegate(ISession innerSession, ISessionStore sessionStore, bool canClose)
{
InnerSession = innerSession;
@@ -70,22 +57,6 @@ public SessionDelegate(ISession innerSession, ISessionStore sessionStore, bool c
_canClose = canClose;
}
- ///
- /// Gets the inner session.
- ///
- /// The inner session.
- public ISession InnerSession { get; }
-
- ///
- /// Gets or sets the session store cookie.
- ///
- /// The session store cookie.
- public object SessionStoreCookie
- {
- get => _cookie;
- set => _cookie = value;
- }
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
@@ -99,7 +70,7 @@ public void Dispose()
///
/// if set to true [closing].
///
- protected IDbConnection DoClose(bool closing)
+ protected IDbConnection? DoClose(bool closing)
{
if (_disposed)
{
@@ -114,9 +85,9 @@ protected IDbConnection DoClose(bool closing)
return null;
}
- internal IDbConnection InternalClose(bool closing)
+ internal IDbConnection? InternalClose(bool closing)
{
- IDbConnection connection = null;
+ IDbConnection? connection = null;
_sessionStore.Remove(this);
@@ -132,6 +103,22 @@ internal IDbConnection InternalClose(bool closing)
return connection;
}
+ ///
+ /// Gets the inner session.
+ ///
+ /// The inner session.
+ public ISession InnerSession { get; }
+
+ ///
+ /// Gets or sets the session store cookie.
+ ///
+ /// The session store cookie.
+ public object? SessionStoreCookie
+ {
+ get => _cookie;
+ set => _cookie = value;
+ }
+
///
/// Returns if the supplied sessions are equal, otherwise.
///
@@ -146,7 +133,8 @@ public static bool AreEqual(ISession left, ISession right)
return ReferenceEquals(sdLeft.InnerSession, sdRight.InnerSession);
}
- throw new NotSupportedException($"{nameof(AreEqual)}: left is {left.GetType().Name} and right is {right.GetType().Name}.");
+ throw new NotSupportedException(
+ $"{nameof(AreEqual)}: left is '{left.GetType().Name}' and right is '{right.GetType().Name}'.");
}
#region ISession Members
@@ -191,10 +179,10 @@ public bool DefaultReadOnly
/// ,
/// because can return .
///
- public ITransaction Transaction =>
- InnerSession?.GetSessionImplementation()?
- .ConnectionManager?
- .CurrentTransaction;
+ public ITransaction? Transaction =>
+ InnerSession.GetSessionImplementation()?
+ .ConnectionManager?
+ .CurrentTransaction;
///
public CacheMode CacheMode
@@ -216,9 +204,9 @@ public ISharedSessionBuilder SessionWithOptions()
}
///
- public DbConnection Close()
+ public DbConnection? Close()
{
- return (DbConnection) DoClose(true);
+ return (DbConnection?) DoClose(true);
}
///
diff --git a/src/Castle.Facilities.NHibernateIntegration/Internal/SessionFactoryActivator.cs b/src/Castle.Facilities.NHibernateIntegration/Internal/SessionFactoryActivator.cs
index b072a7d92..ce2ce9abe 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Internal/SessionFactoryActivator.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Internal/SessionFactoryActivator.cs
@@ -68,12 +68,13 @@ public override object Create(CreationContext context, Burden burden)
///
protected virtual void RaiseCreatingSessionFactory()
{
- var configuration = Model.ExtendedProperties[Constants.SessionFactoryConfiguration] as Configuration;
-
- var contributors = Kernel.ResolveAll();
- foreach (var contributor in contributors)
+ if (Model.ExtendedProperties[Constants.SessionFactoryConfiguration] is Configuration configuration)
{
- contributor.Process(Model.Name, configuration);
+ var contributors = Kernel.ResolveAll();
+ foreach (var contributor in contributors)
+ {
+ contributor.Process(Model.Name, configuration);
+ }
}
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration/Internal/SessionFactoryResolver.cs b/src/Castle.Facilities.NHibernateIntegration/Internal/SessionFactoryResolver.cs
index 65d37fb9b..666a79697 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Internal/SessionFactoryResolver.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Internal/SessionFactoryResolver.cs
@@ -84,7 +84,8 @@ public ISessionFactory GetSessionFactory(string alias)
{
if (!_dictionary.TryGetValue(alias, out var componentKey))
{
- throw new FacilityException($"An {nameof(ISessionFactory)} component was not mapped for the specified alias: {alias}.");
+ throw new FacilityException(
+ $"An '{nameof(ISessionFactory)}' component was not mapped for the specified alias: '{alias}'.");
}
return _kernel.Resolve(componentKey);
diff --git a/src/Castle.Facilities.NHibernateIntegration/Internal/StatelessSessionDelegate.cs b/src/Castle.Facilities.NHibernateIntegration/Internal/StatelessSessionDelegate.cs
index e30ee1602..2170cb1dc 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Internal/StatelessSessionDelegate.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Internal/StatelessSessionDelegate.cs
@@ -36,9 +36,9 @@ namespace Castle.Facilities.NHibernateIntegration
[Serializable]
public class StatelessSessionDelegate : MarshalByRefObject, IStatelessSession
{
- private readonly bool _canClose;
private readonly ISessionStore _sessionStore;
- private object _cookie;
+ private readonly bool _canClose;
+ private object? _cookie;
private bool _disposed;
///
@@ -47,13 +47,6 @@ public class StatelessSessionDelegate : MarshalByRefObject, IStatelessSession
/// The inner session.
/// The session store.
/// Set to true if can close the session.
- ///
- /// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0618
- ///
- /// #pragma warning disable 0618, 0612
- /// #pragma warning restore 0618, 0612
- ///
- ///
public StatelessSessionDelegate(IStatelessSession innerSession, ISessionStore sessionStore, bool canClose)
{
InnerSession = innerSession;
@@ -61,22 +54,6 @@ public StatelessSessionDelegate(IStatelessSession innerSession, ISessionStore se
_canClose = canClose;
}
- ///
- /// Gets the inner session.
- ///
- /// The inner session.
- public IStatelessSession InnerSession { get; }
-
- ///
- /// Gets or sets the session store cookie.
- ///
- /// The session store cookie.
- public object SessionStoreCookie
- {
- get => _cookie;
- set => _cookie = value;
- }
-
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
@@ -90,7 +67,7 @@ public void Dispose()
///
/// if set to true [closing].
///
- protected IDbConnection DoClose(bool closing)
+ protected IDbConnection? DoClose(bool closing)
{
if (_disposed)
{
@@ -105,9 +82,9 @@ protected IDbConnection DoClose(bool closing)
return null;
}
- internal IDbConnection InternalClose(bool closing)
+ internal IDbConnection? InternalClose(bool closing)
{
- IDbConnection connection = null;
+ IDbConnection? connection = null;
_sessionStore.Remove(this);
@@ -124,6 +101,22 @@ internal IDbConnection InternalClose(bool closing)
return connection;
}
+ ///
+ /// Gets the inner session.
+ ///
+ /// The inner session.
+ public IStatelessSession InnerSession { get; }
+
+ ///
+ /// Gets or sets the session store cookie.
+ ///
+ /// The session store cookie.
+ public object? SessionStoreCookie
+ {
+ get => _cookie;
+ set => _cookie = value;
+ }
+
///
/// Returns if the supplied stateless sessions are equal, otherwise.
///
@@ -138,7 +131,8 @@ public static bool AreEqual(IStatelessSession left, IStatelessSession right)
return ReferenceEquals(ssdLeft.InnerSession, ssdRight.InnerSession);
}
- throw new NotSupportedException($"{nameof(AreEqual)}: left is {left.GetType().Name} and right is {right.GetType().Name}.");
+ throw new NotSupportedException(
+ $"{nameof(AreEqual)}: left is '{left.GetType().Name}' and right is '{right.GetType().Name}'.");
}
#region IStatelessSession Members
@@ -168,10 +162,10 @@ public static bool AreEqual(IStatelessSession left, IStatelessSession right)
/// ,
/// because can return .
///
- public ITransaction Transaction =>
- InnerSession?.GetSessionImplementation()?
- .ConnectionManager?
- .CurrentTransaction;
+ public ITransaction? Transaction =>
+ InnerSession.GetSessionImplementation()?
+ .ConnectionManager?
+ .CurrentTransaction;
///
public ISessionImplementor GetSessionImplementation()
diff --git a/src/Castle.Facilities.NHibernateIntegration/NHibernateFacility.cs b/src/Castle.Facilities.NHibernateIntegration/NHibernateFacility.cs
index 9dfc87449..77ee90e55 100644
--- a/src/Castle.Facilities.NHibernateIntegration/NHibernateFacility.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/NHibernateFacility.cs
@@ -21,24 +21,19 @@ namespace Castle.Facilities.NHibernateIntegration
using System.Configuration;
using System.Linq;
- using Builders;
-
- using Core.Configuration;
- using Core.Logging;
-
- using Internal;
-
- using MicroKernel;
- using MicroKernel.Facilities;
- using MicroKernel.Registration;
- using MicroKernel.SubSystems.Conversion;
+ using Castle.Core.Configuration;
+ using Castle.Core.Logging;
+ using Castle.Facilities.NHibernateIntegration.Builders;
+ using Castle.Facilities.NHibernateIntegration.Internal;
+ using Castle.Facilities.NHibernateIntegration.SessionStores;
+ using Castle.MicroKernel;
+ using Castle.MicroKernel.Facilities;
+ using Castle.MicroKernel.Registration;
+ using Castle.MicroKernel.SubSystems.Conversion;
+ using Castle.Services.Transaction;
using NHibernate;
- using Services.Transaction;
-
- using SessionStores;
-
using IInterceptor = NHibernate.IInterceptor;
using ILogger = Core.Logging.ILogger;
using ILoggerFactory = Core.Logging.ILoggerFactory;
@@ -71,7 +66,7 @@ namespace Castle.Facilities.NHibernateIntegration
///
/// public void Save(Data data)
/// {
- /// using(ISession session = _sessionManager.OpenSession())
+ /// using (var session = _sessionManager.OpenSession())
/// {
/// session.Save(data);
/// }
@@ -84,24 +79,25 @@ public class NHibernateFacility : AbstractFacility
public static readonly Type DefaultSessionStoreType = typeof(AsyncLocalSessionStore);
internal const string ConfigurationBuilderConfigurationKey = "configurationBuilder";
+ internal const string UseReflectionOptimizerConfigurationKey = "useReflectionOptimizer";
+ internal const string DefaultFlushModeConfigurationKey = "defaultFlushMode";
+ internal const string IsWebConfigurationKey = "isWeb";
internal const string SessionFactoryIdConfigurationKey = "id";
internal const string SessionFactoryAliasConfigurationKey = "alias";
- internal const string IsWebConfigurationKey = "isWeb";
- internal const string CustomSessionStoreConfigurationKey = "customStore";
- internal const string DefaultFlushModeConfigurationKey = "defaultFlushMode";
+ internal const string SessionStoreConfigurationKey = "sessionStore";
- private const string DefaultConfigurationBuilderKey = "nhfacility.configuration.builder";
- private const string TransactionManagerKey = "nhibernate.transaction.manager";
+ private const string ConfigurationBuilderKey = "nhfacility.configuration.builder";
+ private const string ConfigurationBuilderFactoryKeyFormat = "{0}.configurationBuilder";
+ private const string TransactionManagerKey = "nhfacility.transaction.manager";
private const string SessionFactoryResolverKey = "nhfacility.sessionfactory.resolver";
private const string SessionInterceptorKey = "nhibernate.sessionfactory.interceptor";
- private const string SessionStoreKey = "nhfacility.sessionstore";
- private const string SessionManagerKey = "nhfacility.sessionmanager";
- private const string ConfigurationBuilderForFactoryFormat = "{0}.configurationBuilder";
+ private const string SessionStoreKey = "nhfacility.session.store";
+ private const string SessionManagerKey = "nhfacility.session.manager";
private ILogger _logger = NullLogger.Instance;
private readonly IConfigurationBuilder _configurationBuilder;
- private Type _customConfigurationBuilderType;
+ private Type? _configurationBuilderType;
private readonly NHibernateFacilityConfiguration _facilityConfiguration;
///
@@ -110,14 +106,16 @@ public class NHibernateFacility : AbstractFacility
///
public NHibernateFacility(IConfigurationBuilder configurationBuilder)
{
- _configurationBuilder = configurationBuilder;
+ _configurationBuilder = configurationBuilder ??
+ throw new ArgumentNullException(nameof(configurationBuilder));
_facilityConfiguration = new NHibernateFacilityConfiguration(configurationBuilder);
}
///
/// Initializes a new instance of the class.
///
- public NHibernateFacility() : this(new DefaultConfigurationBuilder())
+ public NHibernateFacility() :
+ this(new DefaultConfigurationBuilder())
{
}
@@ -134,7 +132,7 @@ protected override void Init()
_facilityConfiguration.Init(Kernel, FacilityConfig);
- AssertHasConfig();
+ AssertHasConfiguration();
AssertHasAtLeastOneFactoryConfigured();
RegisterComponents();
ConfigureFacility();
@@ -165,32 +163,30 @@ protected virtual void RegisterComponents()
///
private void RegisterDefaultConfigurationBuilder()
{
- if (!_facilityConfiguration.HasConcreteConfigurationBuilder())
+ if (!_facilityConfiguration.HasConcreteConfigurationBuilder)
{
- _customConfigurationBuilderType = _facilityConfiguration.GetConfigurationBuilderType();
+ _configurationBuilderType = _facilityConfiguration.GetConfigurationBuilderType();
- if (_facilityConfiguration.HasConfigurationBuilderType())
+ if (_facilityConfiguration.HasConfigurationBuilderType)
{
- if (!typeof(IConfigurationBuilder).IsAssignableFrom(_customConfigurationBuilderType))
+ if (!typeof(IConfigurationBuilder).IsAssignableFrom(_configurationBuilderType))
{
throw new FacilityException(
- string.Format(
- "ConfigurationBuilder type '{0}' is invalid. The type must implement the IConfigurationBuilder contract.",
- _customConfigurationBuilderType.FullName));
+ $"ConfigurationBuilder type '{_configurationBuilderType.FullName}' is invalid. The type must implement the IConfigurationBuilder contract.");
}
}
Kernel.Register(
Component.For()
- .ImplementedBy(_customConfigurationBuilderType)
- .Named(DefaultConfigurationBuilderKey));
+ .ImplementedBy(_configurationBuilderType)
+ .Named(ConfigurationBuilderKey));
}
else
{
Kernel.Register(
Component.For()
.Instance(_configurationBuilder)
- .Named(DefaultConfigurationBuilderKey));
+ .Named(ConfigurationBuilderKey));
}
}
@@ -222,7 +218,7 @@ protected void RegisterSessionStore()
///
protected void RegisterSessionManager()
{
- var defaultFlushMode = _facilityConfiguration.FlushMode;
+ var defaultFlushMode = _facilityConfiguration.DefaultFlushMode;
if (!string.IsNullOrEmpty(defaultFlushMode))
{
@@ -249,7 +245,7 @@ protected void RegisterTransactionManager()
{
if (!Kernel.HasComponent(typeof(ITransactionManager)))
{
- _logger.Info($"No {nameof(ITransactionManager)} implementation registered on Kernel, registering default {nameof(ITransactionManager)} implementation.");
+ _logger.Info($"No '{nameof(ITransactionManager)}' implementation registered on Kernel, registering default '{nameof(ITransactionManager)}' implementation.");
Kernel.Register(
Component.For()
@@ -273,9 +269,9 @@ protected void ConfigureFacility()
var firstFactory = true;
- foreach (var factoryConfig in _facilityConfiguration.Factories)
+ foreach (var factoryConfiguration in _facilityConfiguration.FactoryConfigurations)
{
- ConfigureFactories(factoryConfig, sessionFactoryResolver, firstFactory);
+ ConfigureFactories(factoryConfiguration, sessionFactoryResolver, firstFactory);
firstFactory = false;
}
@@ -292,7 +288,7 @@ protected void ConfigureFacility()
///
private void ConfigureReflectionOptimizer()
{
- NHibernate.Cfg.Environment.UseReflectionOptimizer = _facilityConfiguration.ShouldUseReflectionOptimizer();
+ NHibernate.Cfg.Environment.UseReflectionOptimizer = _facilityConfiguration.UseReflectionOptimizer;
}
///
@@ -301,14 +297,16 @@ private void ConfigureReflectionOptimizer()
/// The config.
/// The session factory resolver.
/// if set to true [first factory].
- protected void ConfigureFactories(NHibernateFactoryConfiguration factoryConfiguration, ISessionFactoryResolver sessionFactoryResolver, bool firstFactory)
+ protected void ConfigureFactories(NHibernateFactoryConfiguration factoryConfiguration,
+ ISessionFactoryResolver sessionFactoryResolver,
+ bool firstFactory)
{
var id = factoryConfiguration.Id;
if (string.IsNullOrEmpty(id))
{
var message = "You must provide a valid 'id' attribute for the 'factory' node. " +
- "This id is used as key for the ISessionFactory component registered on the container.";
+ "This id is used as key for the 'ISessionFactory' component registered on the container.";
throw new ConfigurationErrorsException(message);
}
@@ -317,7 +315,7 @@ protected void ConfigureFactories(NHibernateFactoryConfiguration factoryConfigur
if (!firstFactory && string.IsNullOrEmpty(alias))
{
var message = "You must provide a valid 'alias' attribute for the 'factory' node. " +
- "This id is used to obtain the ISession implementation from the SessionManager.";
+ "This id is used to obtain the 'ISession' implementation from the 'SessionManager'.";
throw new ConfigurationErrorsException(message);
}
@@ -327,7 +325,7 @@ protected void ConfigureFactories(NHibernateFactoryConfiguration factoryConfigur
}
var configurationBuilderType = factoryConfiguration.ConfigurationBuilderType;
- var configurationBuilderKey = string.Format(ConfigurationBuilderForFactoryFormat, id);
+ var configurationBuilderFactoryKey = string.Format(ConfigurationBuilderFactoryKeyFormat, id);
IConfigurationBuilder configurationBuilder;
if (string.IsNullOrEmpty(configurationBuilderType))
{
@@ -338,17 +336,17 @@ protected void ConfigureFactories(NHibernateFactoryConfiguration factoryConfigur
Kernel.Register(
Component.For()
.ImplementedBy(Type.GetType(configurationBuilderType))
- .Named(configurationBuilderKey));
- configurationBuilder = Kernel.Resolve(configurationBuilderKey);
+ .Named(configurationBuilderFactoryKey));
+ configurationBuilder = Kernel.Resolve(configurationBuilderFactoryKey);
}
var configuration = configurationBuilder.GetConfiguration(factoryConfiguration.GetConfiguration());
- // Registers the Configuration object.
+ // Registers NHibernate Configuration.
Kernel.Register(
Component.For()
.Instance(configuration)
- .Named(string.Format("{0}.cfg", id)));
+ .Named($"{id}.cfg"));
// If a Session Factory level interceptor was provided, we use it.
if (Kernel.HasComponent(SessionInterceptorKey))
@@ -356,7 +354,7 @@ protected void ConfigureFactories(NHibernateFactoryConfiguration factoryConfigur
configuration.Interceptor = Kernel.Resolve(SessionInterceptorKey);
}
- // Registers the ISessionFactory as a component.
+ // Registers NHibernate ISessionFactory.
Kernel.Register(
Component.For()
.Named(id)
@@ -364,7 +362,7 @@ protected void ConfigureFactories(NHibernateFactoryConfiguration factoryConfigur
.ExtendedProperties(Property.ForKey(Constants.SessionFactoryConfiguration).Eq(configuration))
.LifeStyle.Singleton);
- sessionFactoryResolver.RegisterAliasComponentIdMapping(alias, id);
+ sessionFactoryResolver.RegisterAliasComponentIdMapping(alias!, id!);
}
#endregion
@@ -373,7 +371,7 @@ protected void ConfigureFactories(NHibernateFactoryConfiguration factoryConfigur
private void AssertHasAtLeastOneFactoryConfigured()
{
- if (_facilityConfiguration.HasValidFactory())
+ if (_facilityConfiguration.HasValidFactory)
{
return;
}
@@ -381,16 +379,16 @@ private void AssertHasAtLeastOneFactoryConfigured()
var factoriesConfig = FacilityConfig.Children["factory"];
if (factoriesConfig == null)
{
- var message = $"You need to configure at least one factory to use the {nameof(NHibernateFacility)}.";
+ const string message = $"You need to configure at least one factory to use the '{nameof(NHibernateFacility)}'.";
throw new ConfigurationErrorsException(message);
}
}
- private void AssertHasConfig()
+ private void AssertHasConfiguration()
{
- if (!_facilityConfiguration.IsValid())
+ if (!_facilityConfiguration.IsValid)
{
- var message = $"The {nameof(NHibernateFacility)} requires configuration.";
+ var message = $"The '{nameof(NHibernateFacility)}' requires configuration.";
throw new ConfigurationErrorsException(message);
}
}
@@ -451,15 +449,16 @@ public NHibernateFacility SessionStore()
internal class NHibernateFacilityConfiguration
{
- private IKernel _kernel;
- private IConfiguration _facilityConfiguration;
- private IConfigurationBuilder _configurationBuilder;
- private Type _configurationBuilderType;
- private Type _customSessionStoreType;
- private bool _isWeb;
+ private Type _configurationBuilderType = null!;
private readonly bool _useReflectionOptimizer = false;
+ private bool _isWeb;
+ private Type _sessionStoreType = null!;
+
+ private IKernel _kernel = null!;
+ private IConfiguration _facilityConfiguration = null!;
+ private IConfigurationBuilder? _configurationBuilder;
- public IEnumerable Factories { get; set; }
+ public IEnumerable FactoryConfigurations { get; set; }
///
///
@@ -468,13 +467,10 @@ public NHibernateFacilityConfiguration(IConfigurationBuilder configurationBuilde
{
_configurationBuilder = configurationBuilder;
- Factories = Enumerable.Empty();
+ FactoryConfigurations = Enumerable.Empty();
}
- public bool OnWeb =>
- _isWeb;
-
- public string FlushMode { get; set; }
+ public string? DefaultFlushMode { get; set; }
///
///
@@ -486,20 +482,19 @@ public void Init(IKernel kernel, IConfiguration facilityConfiguration)
_kernel = kernel;
_facilityConfiguration = facilityConfiguration;
- if (ConfigurationIsValid())
+ if (ConfigurationIsValid)
{
ConfigureWithExternalConfiguration();
}
else
{
- Factories =
- new[]
+ FactoryConfigurations = new[]
+ {
+ new NHibernateFactoryConfiguration(new MutableConfiguration("factory"))
{
- new NHibernateFactoryConfiguration(new MutableConfiguration("factory"))
- {
- Id = "factory_1"
- }
- };
+ Id = "factory_1"
+ },
+ };
}
}
@@ -518,106 +513,87 @@ private void ConfigureWithExternalConfiguration()
catch (ConverterException)
{
throw new FacilityException(
- string.Format(
- "ConfigurationBuilder type '{0}' is invalid or not found.",
- builder));
+ $"ConfigurationBuilder type '{builder}' is invalid or not found.");
}
}
BuildFactories();
- if (_facilityConfiguration.Attributes[NHibernateFacility.CustomSessionStoreConfigurationKey] != null)
+ DefaultFlushMode = _facilityConfiguration.Attributes[NHibernateFacility.DefaultFlushModeConfigurationKey];
+
+ bool.TryParse(_facilityConfiguration.Attributes[NHibernateFacility.IsWebConfigurationKey], out _isWeb);
+
+ if (_facilityConfiguration.Attributes[NHibernateFacility.SessionStoreConfigurationKey] != null)
{
- var customStoreType = _facilityConfiguration.Attributes[NHibernateFacility.CustomSessionStoreConfigurationKey];
+ var sessionStoreType = _facilityConfiguration.Attributes[NHibernateFacility.SessionStoreConfigurationKey];
var converter = (ITypeConverter) _kernel.GetSubSystem(SubSystemConstants.ConversionManagerKey);
- SessionStore((Type) converter.PerformConversion(customStoreType, typeof(Type)));
+ SessionStore((Type) converter.PerformConversion(sessionStoreType, typeof(Type)));
}
+ }
- FlushMode = _facilityConfiguration.Attributes[NHibernateFacility.DefaultFlushModeConfigurationKey];
+ public bool IsValid =>
+ _facilityConfiguration != null ||
+ _configurationBuilder != null ||
+ _configurationBuilderType != null;
- bool.TryParse(_facilityConfiguration.Attributes[NHibernateFacility.IsWebConfigurationKey], out _isWeb);
- }
+ private bool ConfigurationIsValid =>
+ _facilityConfiguration != null &&
+ _facilityConfiguration.Children.Count > 0;
- private bool ConfigurationIsValid()
- {
- return _facilityConfiguration != null && _facilityConfiguration.Children.Count > 0;
- }
+ public bool HasValidFactory =>
+ FactoryConfigurations.Any();
private void BuildFactories()
{
- Factories =
+ FactoryConfigurations =
_facilityConfiguration.Children
- .Select(config => new NHibernateFactoryConfiguration(config));
- }
-
- public void ConfigurationBuilder(Type type)
- {
- _configurationBuilder = null;
- _configurationBuilderType = type;
+ .Select(configuration =>
+ new NHibernateFactoryConfiguration(configuration));
}
- public void SessionStore(Type type)
- {
- if (!typeof(ISessionStore).IsAssignableFrom(type))
- {
- var message = $"The specified customSessionStore type '{type}' " +
- $"does not implement the {nameof(ISessionStore)} interface.";
- throw new ConfigurationErrorsException(message);
- }
+ public bool HasConfigurationBuilderType =>
+ _configurationBuilderType != null;
- _customSessionStoreType = type;
- }
+ public bool HasConcreteConfigurationBuilder =>
+ _configurationBuilder != null && !HasConfigurationBuilderType;
- public void ConfigurationBuilder(IConfigurationBuilder configurationBuilder)
- {
- _configurationBuilder = configurationBuilder;
- }
-
- public void IsWeb()
+ public Type GetConfigurationBuilderType()
{
- _isWeb = true;
+ return _configurationBuilderType;
}
- public bool IsValid()
+ public void ConfigurationBuilder(Type type)
{
- return _facilityConfiguration != null ||
- _configurationBuilder != null ||
- _configurationBuilderType != null;
+ _configurationBuilderType = type;
+ _configurationBuilder = null;
}
- public bool HasValidFactory()
+ public void ConfigurationBuilder(IConfigurationBuilder configurationBuilder)
{
- return Factories.Count() > 0;
+ _configurationBuilder = configurationBuilder;
}
- public bool ShouldUseReflectionOptimizer()
+ public bool UseReflectionOptimizer
{
- if (_facilityConfiguration != null)
+ get
{
- if (bool.TryParse(_facilityConfiguration.Attributes["useReflectionOptimizer"], out var result))
+ if (_facilityConfiguration != null)
{
- return result;
+ if (bool.TryParse(_facilityConfiguration.Attributes[NHibernateFacility.UseReflectionOptimizerConfigurationKey], out var result))
+ {
+ return result;
+ }
+
+ return false;
}
- return false;
+ return _useReflectionOptimizer;
}
-
- return _useReflectionOptimizer;
- }
-
- public bool HasConcreteConfigurationBuilder()
- {
- return _configurationBuilder != null && !HasConfigurationBuilderType();
}
- public Type GetConfigurationBuilderType()
- {
- return _configurationBuilderType;
- }
-
- public bool HasConfigurationBuilderType()
+ public void IsWeb()
{
- return _configurationBuilderType != null;
+ _isWeb = true;
}
public Type GetSessionStoreType()
@@ -629,13 +605,25 @@ public Type GetSessionStoreType()
sessionStoreType = typeof(WebSessionStore);
}
- if (_customSessionStoreType != null)
+ if (_sessionStoreType != null)
{
- sessionStoreType = _customSessionStoreType;
+ sessionStoreType = _sessionStoreType;
}
return sessionStoreType;
}
+
+ public void SessionStore(Type type)
+ {
+ if (!typeof(ISessionStore).IsAssignableFrom(type))
+ {
+ var message = $"The specified sessionStore type '{type}' " +
+ $"does not implement the '{nameof(ISessionStore)}' interface.";
+ throw new ConfigurationErrorsException(message);
+ }
+
+ _sessionStoreType = type;
+ }
}
///
@@ -650,9 +638,8 @@ public class NHibernateFactoryConfiguration
///
public NHibernateFactoryConfiguration(IConfiguration facilityConfiguration)
{
- _facilityConfiguration =
- facilityConfiguration ??
- throw new ArgumentNullException(nameof(facilityConfiguration));
+ _facilityConfiguration = facilityConfiguration ??
+ throw new ArgumentNullException(nameof(facilityConfiguration));
Id = facilityConfiguration.Attributes[NHibernateFacility.SessionFactoryIdConfigurationKey];
Alias = facilityConfiguration.Attributes[NHibernateFacility.SessionFactoryAliasConfigurationKey];
@@ -662,17 +649,17 @@ public NHibernateFactoryConfiguration(IConfiguration facilityConfiguration)
///
/// Get or sets the factory Id.
///
- public string Id { get; set; }
+ public string? Id { get; set; }
///
/// Gets or sets the factory Alias.
///
- public string Alias { get; set; }
+ public string? Alias { get; set; }
///
/// Gets or sets the factory ConfigurationBuilder.
///
- public string ConfigurationBuilderType { get; set; }
+ public string? ConfigurationBuilderType { get; set; }
///
/// Constructs an IConfiguration instance for this factory.
diff --git a/src/Castle.Facilities.NHibernateIntegration/SessionStores/AbstractDictionaryStackSessionStore.cs b/src/Castle.Facilities.NHibernateIntegration/SessionStores/AbstractDictionaryStackSessionStore.cs
index c1688ec8e..565d0b257 100644
--- a/src/Castle.Facilities.NHibernateIntegration/SessionStores/AbstractDictionaryStackSessionStore.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/SessionStores/AbstractDictionaryStackSessionStore.cs
@@ -29,11 +29,9 @@ public abstract class AbstractDictionaryStackSessionStore : AbstractSessionStore
protected AbstractDictionaryStackSessionStore()
{
SessionSlotKey =
- string.Format("nh.facility.stacks.session.{0}",
- Guid.NewGuid());
+ $"nh.facility.stacks.session.{Guid.NewGuid()}";
StatelessSessionSlotKey =
- string.Format("nh.facility.stacks.statelessSession.{0}",
- Guid.NewGuid());
+ $"nh.facility.stacks.statelessSession.{Guid.NewGuid()}";
}
///
@@ -47,7 +45,7 @@ protected AbstractDictionaryStackSessionStore()
protected string StatelessSessionSlotKey { get; }
///
- protected override Stack GetSessionStackFor(string alias)
+ protected override Stack GetSessionStackFor(string? alias)
{
lock (_lock)
{
@@ -72,7 +70,7 @@ protected override Stack GetSessionStackFor(string alias)
dictionary[alias] = stack;
}
- return stack;
+ return stack!;
}
}
@@ -89,7 +87,7 @@ protected override Stack GetSessionStackFor(string alias)
protected abstract void StoreSessionDictionary(IDictionary> dictionary);
///
- protected override Stack GetStatelessSessionStackFor(string alias)
+ protected override Stack GetStatelessSessionStackFor(string? alias)
{
lock (_lock)
{
@@ -114,7 +112,7 @@ protected override Stack GetStatelessSessionStackFor(s
dictionary[alias] = stack;
}
- return stack;
+ return stack!;
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration/SessionStores/AbstractSessionStore.cs b/src/Castle.Facilities.NHibernateIntegration/SessionStores/AbstractSessionStore.cs
index d6ea5349f..9d329c036 100644
--- a/src/Castle.Facilities.NHibernateIntegration/SessionStores/AbstractSessionStore.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/SessionStores/AbstractSessionStore.cs
@@ -33,7 +33,7 @@ public abstract class AbstractSessionStore : MarshalByRefObject, ISessionStore
///
///
///
- public bool IsCurrentActivityEmptyFor(string alias)
+ public bool IsCurrentActivityEmptyFor(string? alias)
{
var sessionStack = GetSessionStackFor(alias);
var statelessSessionStack = GetStatelessSessionStackFor(alias);
@@ -47,7 +47,7 @@ public bool IsCurrentActivityEmptyFor(string alias)
///
///
///
- public SessionDelegate FindCompatibleSession(string alias)
+ public SessionDelegate? FindCompatibleSession(string? alias)
{
var stack = GetSessionStackFor(alias);
@@ -79,23 +79,26 @@ public void Store(string alias, SessionDelegate session)
///
public void Remove(SessionDelegate session)
{
- var stack = (Stack) session.SessionStoreCookie;
+ var stack = (Stack?) session.SessionStoreCookie;
if (stack == null)
{
- throw new InvalidProgramException($"{nameof(AbstractSessionStore)}.{nameof(Remove)} called with no cookie.");
+ throw new InvalidProgramException(
+ $"'{nameof(AbstractSessionStore)}.{nameof(Remove)}({nameof(SessionDelegate)})' called with no cookie.");
}
if (stack.Count == 0)
{
- throw new InvalidProgramException($"{nameof(AbstractSessionStore)}.{nameof(Remove)} called for an empty stack.");
+ throw new InvalidProgramException(
+ $"'{nameof(AbstractSessionStore)}.{nameof(Remove)}({nameof(SessionDelegate)})' called for an empty stack.");
}
var current = stack.Peek() as ISession;
if (session != current)
{
- throw new InvalidProgramException($"{nameof(AbstractSessionStore)}.{nameof(Remove)} tried to " +
- $"remove an {nameof(ISession)} which is not on the top or not in the stack at all.");
+ throw new InvalidProgramException(
+ $"'{nameof(AbstractSessionStore)}.{nameof(Remove)}({nameof(SessionDelegate)})' tried to " +
+ $"remove an '{nameof(ISession)}' which is not on the top or not in the stack at all.");
}
stack.Pop();
@@ -108,7 +111,7 @@ public void Remove(SessionDelegate session)
///
/// The alias.
///
- protected abstract Stack GetSessionStackFor(string alias);
+ protected abstract Stack GetSessionStackFor(string? alias);
///
/// Find a previously stored for the given alias if available.
@@ -116,7 +119,7 @@ public void Remove(SessionDelegate session)
///
///
///
- public StatelessSessionDelegate FindCompatibleStatelessSession(string alias)
+ public StatelessSessionDelegate? FindCompatibleStatelessSession(string? alias)
{
var stack = GetStatelessSessionStackFor(alias);
@@ -148,23 +151,26 @@ public void Store(string alias, StatelessSessionDelegate statelessSession)
///
public void Remove(StatelessSessionDelegate statelessSession)
{
- var stack = (Stack) statelessSession.SessionStoreCookie;
+ var stack = (Stack?) statelessSession.SessionStoreCookie;
if (stack == null)
{
- throw new InvalidProgramException($"{nameof(AbstractSessionStore)}.{nameof(Remove)} called with no cookie.");
+ throw new InvalidProgramException(
+ $"'{nameof(AbstractSessionStore)}.{nameof(Remove)}({nameof(StatelessSessionDelegate)})' called with no cookie.");
}
if (stack.Count == 0)
{
- throw new InvalidProgramException($"{nameof(AbstractSessionStore)}.{nameof(Remove)} called for an empty stack.");
+ throw new InvalidProgramException(
+ $"'{nameof(AbstractSessionStore)}.{nameof(Remove)}({nameof(StatelessSessionDelegate)})' called for an empty stack.");
}
var current = stack.Peek() as IStatelessSession;
if (statelessSession != current)
{
- throw new InvalidProgramException($"{nameof(AbstractSessionStore)}.{nameof(Remove)} tried to " +
- $"remove an {nameof(IStatelessSession)} which is not on the top or not in the stack at all.");
+ throw new InvalidProgramException(
+ $"'{nameof(AbstractSessionStore)}.{nameof(Remove)}({nameof(StatelessSessionDelegate)})' tried to " +
+ $"remove an '{nameof(IStatelessSession)}' which is not on the top or not in the stack at all.");
}
stack.Pop();
@@ -177,6 +183,6 @@ public void Remove(StatelessSessionDelegate statelessSession)
///
/// The alias.
///
- protected abstract Stack GetStatelessSessionStackFor(string alias);
+ protected abstract Stack GetStatelessSessionStackFor(string? alias);
}
}
diff --git a/src/Castle.Facilities.NHibernateIntegration/SessionStores/AsyncLocalSessionStore.cs b/src/Castle.Facilities.NHibernateIntegration/SessionStores/AsyncLocalSessionStore.cs
index c2ea13def..cbad5dfec 100644
--- a/src/Castle.Facilities.NHibernateIntegration/SessionStores/AsyncLocalSessionStore.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/SessionStores/AsyncLocalSessionStore.cs
@@ -30,7 +30,7 @@ public class AsyncLocalSessionStore : AbstractDictionaryStackSessionStore
protected override IDictionary> GetSessionDictionary()
{
- return _sessionAsyncLocal.Value;
+ return _sessionAsyncLocal.Value!;
}
protected override void StoreSessionDictionary(IDictionary> dictionary)
@@ -40,7 +40,7 @@ protected override void StoreSessionDictionary(IDictionary> GetStatelessSessionDictionary()
{
- return _statelessSessionAsyncLocal.Value;
+ return _statelessSessionAsyncLocal.Value!;
}
protected override void StoreStatelessSessionDictionary(IDictionary> dictionary)
diff --git a/src/Castle.Facilities.NHibernateIntegration/SessionStores/CallContextSessionStore.cs b/src/Castle.Facilities.NHibernateIntegration/SessionStores/CallContextSessionStore.cs
index 6b188223f..fd07b9209 100644
--- a/src/Castle.Facilities.NHibernateIntegration/SessionStores/CallContextSessionStore.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/SessionStores/CallContextSessionStore.cs
@@ -42,7 +42,7 @@ public class CallContextSessionStore : AbstractDictionaryStackSessionStore
protected override IDictionary> GetSessionDictionary()
{
#if NETFRAMEWORK
- return CallContext.GetData(SessionSlotKey) as IDictionary>;
+ return (IDictionary>) CallContext.GetData(SessionSlotKey);
#else
throw new PlatformNotSupportedException();
#endif
@@ -60,7 +60,7 @@ protected override void StoreSessionDictionary(IDictionary> GetStatelessSessionDictionary()
{
#if NETFRAMEWORK
- return CallContext.GetData(StatelessSessionSlotKey) as IDictionary>;
+ return (IDictionary>) CallContext.GetData(StatelessSessionSlotKey);
#else
throw new PlatformNotSupportedException();
#endif
diff --git a/src/Castle.Facilities.NHibernateIntegration/SessionStores/LogicalCallContextSessionStore.cs b/src/Castle.Facilities.NHibernateIntegration/SessionStores/LogicalCallContextSessionStore.cs
index 5d2b65fee..8b0a67a45 100644
--- a/src/Castle.Facilities.NHibernateIntegration/SessionStores/LogicalCallContextSessionStore.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/SessionStores/LogicalCallContextSessionStore.cs
@@ -42,7 +42,7 @@ public class LogicalCallContextSessionStore : AbstractDictionaryStackSessionStor
protected override IDictionary> GetSessionDictionary()
{
#if NETFRAMEWORK
- return CallContext.LogicalGetData(SessionSlotKey) as IDictionary>;
+ return (IDictionary>) CallContext.LogicalGetData(SessionSlotKey);
#else
throw new PlatformNotSupportedException();
#endif
@@ -60,7 +60,7 @@ protected override void StoreSessionDictionary(IDictionary> GetStatelessSessionDictionary()
{
#if NETFRAMEWORK
- return CallContext.LogicalGetData(StatelessSessionSlotKey) as IDictionary>;
+ return (IDictionary>) CallContext.LogicalGetData(StatelessSessionSlotKey);
#else
throw new PlatformNotSupportedException();
#endif
diff --git a/src/Castle.Facilities.NHibernateIntegration/SessionStores/WebSessionStore.cs b/src/Castle.Facilities.NHibernateIntegration/SessionStores/WebSessionStore.cs
index f80a59aad..feb13beae 100644
--- a/src/Castle.Facilities.NHibernateIntegration/SessionStores/WebSessionStore.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/SessionStores/WebSessionStore.cs
@@ -22,30 +22,30 @@ namespace Castle.Facilities.NHibernateIntegration.SessionStores
using System.Web;
#endif
- using MicroKernel.Facilities;
+ using Castle.MicroKernel.Facilities;
#if NET
using Microsoft.AspNetCore.Http;
#endif
-#if NETFRAMEWORK
+#if NET
///
/// An implementation of
/// which relies on .
- /// This is intended for legacy ASP.NET projects.
+ /// This is intended for ASP.NET (Core) projects.
///
#else
///
/// An implementation of
/// which relies on .
- /// This is intended for ASP.NET (Core) projects.
+ /// This is intended for legacy ASP.NET projects.
///
#endif
public class WebSessionStore : AbstractDictionaryStackSessionStore
{
#if NET
[CLSCompliant(false)]
- public IHttpContextAccessor HttpContextAccessor { get; set; }
+ public IHttpContextAccessor? HttpContextAccessor { get; set; }
#endif
protected override IDictionary> GetSessionDictionary()
@@ -70,34 +70,30 @@ protected override void StoreStatelessSessionDictionary(IDictionary(string key)
{
-#if NETFRAMEWORK
- var value = GetWebContext().Items[key];
-#else
+#if NET
if (!GetWebContext().Items.TryGetValue(key, out var value))
{
- return default;
+ return default!;
}
+#else
+ var value = GetWebContext().Items[key];
#endif
- return (T) value;
+ return (T) value!;
}
private void StoreSessionDictionaryInWebContext(string key, T value)
{
-#if NETFRAMEWORK
- GetWebContext().Items[key] = value;
-#else
GetWebContext().Items[key] = value;
-#endif
}
-#if NETFRAMEWORK
+#if NET
private HttpContext GetWebContext()
{
- var context = HttpContext.Current;
+ var context = HttpContextAccessor?.HttpContext;
if (context == null)
{
- throw new FacilityException($"{nameof(WebSessionStore)}: Could not obtain reference to {nameof(HttpContext)}.");
+ throw new FacilityException($"'{nameof(WebSessionStore)}': Could not obtain reference to '{nameof(HttpContext)}'.");
}
return context;
@@ -105,10 +101,10 @@ private HttpContext GetWebContext()
#else
private HttpContext GetWebContext()
{
- var context = HttpContextAccessor.HttpContext;
+ var context = HttpContext.Current;
if (context == null)
{
- throw new FacilityException($"{nameof(WebSessionStore)}: Could not obtain reference to {nameof(HttpContext)}.");
+ throw new FacilityException($"'{nameof(WebSessionStore)}': Could not obtain reference to '{nameof(HttpContext)}'.");
}
return context;
diff --git a/src/Castle.Facilities.NHibernateIntegration/Util/DictionaryExtensions.cs b/src/Castle.Facilities.NHibernateIntegration/Util/DictionaryExtensions.cs
new file mode 100644
index 000000000..9b9590d18
--- /dev/null
+++ b/src/Castle.Facilities.NHibernateIntegration/Util/DictionaryExtensions.cs
@@ -0,0 +1,29 @@
+namespace Castle.Facilities.NHibernateIntegration.Util
+{
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+
+ public static class DictionaryExtensions
+ {
+ public static bool TryGetValueAs(
+ this IDictionary dictionary,
+ TKey key,
+ [MaybeNullWhen(false)] out TValueAs? valueAs)
+ where TValueAs : TValue
+ {
+ if (dictionary.TryGetValue(key, out var value))
+ {
+ if (value is TValueAs validValueAs)
+ {
+ valueAs = validValueAs;
+
+ return true;
+ }
+ }
+
+ valueAs = default;
+
+ return false;
+ }
+ }
+}
diff --git a/src/Castle.Facilities.NHibernateIntegration/Util/ReflectionUtility.cs b/src/Castle.Facilities.NHibernateIntegration/Util/ReflectionUtility.cs
index 0cc40dd96..4ed2d265a 100644
--- a/src/Castle.Facilities.NHibernateIntegration/Util/ReflectionUtility.cs
+++ b/src/Castle.Facilities.NHibernateIntegration/Util/ReflectionUtility.cs
@@ -28,18 +28,18 @@ public class ReflectionUtility
{
private static readonly BindingFlags BindingFlags =
BindingFlags.Instance |
- BindingFlags.GetProperty |
BindingFlags.Public |
- BindingFlags.NonPublic;
+ BindingFlags.NonPublic |
+ BindingFlags.GetProperty;
///
/// Gets the readable (non indexed) properties names and values.
/// The keys holds the names of the properties.
/// The values are the values of the properties.
///
- public static IDictionary GetPropertiesDictionary(object obj)
+ public static IDictionary GetPropertiesDictionary(object obj)
{
- var dictionary = new Dictionary();
+ var dictionary = new Dictionary();
foreach (var property in obj.GetType().GetProperties(BindingFlags))
{