Use WebApplicationFactory to test CoreWCF endpoints with AutoFac DI - integration-testing

I have a CoreWCF project with Autofac DI and I want to create some Integration Tests using a custom WebApplicationfactory.
I have used the custom WebApplicationFactory code for Autofac suggested here
https://github.com/autofac/Autofac/issues/1207 by Alistair Evans
This works fine for WebApi endpoints but it does not work for my CoreWCF endpoints.
What I found was that the Microsoft.AspNetCore.TestHost.TestServer that is created does not define the Features property with any IServerAddressesFeature. This causes a problem when the CoreWCF.ServiceObjectModel ApplyConfiguration is executed.
I have got around this by using reflection to set the Features property in the CreateServiceProvider method of the CustomServiceProviderFactory as shown below but does anybody know if there is a better way around this.
/// Enables in-memory integration testing for CoreWCF (outside-in testing via <see cref="HttpClient"/>).
///
/// Use these tests to exercise the entire HTTP stack, rather than create in-process ServiceModel channels.
///
/// <see href="https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1"/>
/// <seealso href="https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.1"/>
/// </summary>
/// <typeparam name="TStartup"></typeparam>
public class WcfWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
private ILifetimeScope _container;
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureTestContainer<ContainerBuilder>(container =>
{
container.RegisterBuildCallback(BuildCallback);
});
builder.ConfigureTestServices(services =>
{
});
}
private void BuildCallback(ILifetimeScope obj)
{
_container = obj;
}
protected override IHost CreateHost(IHostBuilder builder)
{
builder.UseServiceProviderFactory(new CustomServiceProviderFactory(ClientOptions.BaseAddress.ToString()));
return base.CreateHost(builder);
}
protected override IHostBuilder? CreateHostBuilder()
{
return base.CreateHostBuilder();
}
}
/// <summary>
/// Based upon https://github.com/dotnet/aspnetcore/issues/14907#issuecomment-620750841 - only necessary because of an issue in ASP.NET Core
/// </summary>
public class CustomServiceProviderFactory : IServiceProviderFactory<ContainerBuilder>
{
private readonly string _testServerBaseAddress;
private AutofacServiceProviderFactory _wrapped;
private IServiceCollection _services;
public CustomServiceProviderFactory(string testServerBaseAddress)
{
_testServerBaseAddress = testServerBaseAddress;
_wrapped = new AutofacServiceProviderFactory();
}
public ContainerBuilder CreateBuilder(IServiceCollection services)
{
// Store the services for later.
_services = services;
return _wrapped.CreateBuilder(services);
}
public IServiceProvider CreateServiceProvider(ContainerBuilder containerBuilder)
{
var sp = _services.BuildServiceProvider();
#pragma warning disable CS0612 // Type or member is obsolete
var filters = sp.GetRequiredService<IEnumerable<IStartupConfigureContainerFilter<ContainerBuilder>>>();
#pragma warning restore CS0612 // Type or member is obsolete
foreach (var filter in filters)
{
filter.ConfigureContainer(b => { })(containerBuilder);
}
var serviceProvider = _wrapped.CreateServiceProvider(containerBuilder);
// The CoreWCF.ServiceObjectModel ApplyConfiguration expects there to be at least one IServerAddressesFeature
// This is normally present for the Kestrel webserver but for the TestServer in the Microsoft.AspNetCore.TestHost namespace does not seem to populate it
// Had to use Refelction to set this since the Set method causes a containerBuilder Build operation
var addresses = new ServerAddressesFeature();
addresses.Addresses.Add(_testServerBaseAddress);
var features = new FeatureCollection();
features.Set<IServerAddressesFeature>(addresses);
var testServer = serviceProvider.GetRequiredService<IServer>();
var field = typeof(TestServer).GetField("<Features>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);
field.SetValue(testServer, features);
return serviceProvider;
}
}
}

I have found some clue in https://stackoverflow.com/a/48547597/3299257
Specifically in the announcement
Hosting no longer adds default server address when no address is explicitly configured
The WebHost will no longer add the default server address of http://localhost:5000 to the IServerAddressesFeature when none is specified. The configuration of the default server address will now be a responsibility of the server.
Addresses specified in IServerAddressesFeature are intended to be used by servers as a fallback when no explicit address is specified directly.
Adding feature was discussed here https://github.com/dotnet/aspnetcore/issues/5931 and came to conclusion that it won't be implemented in TestServer.
In my test scenario I do not use full WebApplicationFactory, but rather directly utilize TestServer so I could make a simpler soultion:
var addresses = new ServerAddressesFeature();
addresses.Addresses.Add("http://localhost");
var features = new FeatureCollection();
features.Set<IServerAddressesFeature>(addresses);
return new TestServer(builder, features);
In your scenario:
(sorry, this is not verified), you could use WebApplicationFactory.WithWebHostBuilder and then, invoke .UseTestServer constructing your own TestServer and providing feature collection in the second argument.
factory.WithWebHostBuilder(builder => {
var addresses = new ServerAddressesFeature();
addresses.Addresses.Add("http://localhost");
var features = new FeatureCollection();
features.Set<IServerAddressesFeature>(addresses);
builder.UseTestServer(new TestServer(builder, features));
});

Related

Can ASP.NET Core 7 with Blazor use NavigateToLogin with a domain hint?

When using the new .NavigateToLogin in a Blazor app in .NET 7 as recommended here, how do I pass a domain hint when calling NavigateToLogin (or NavigateToLogout)? Or is there a way via setup to make the domain hint be added automatically?
Without the domain hint, my users now have an extra step for both log in and out. (I am using MSAL for Open ID Connect with Azure AD.)
From this page, it appears as though I can new-up a InteractiveRequestOptions object, run options.TryAddAdditionalParameter("domain_hint", "mydomain.com");, and pass that into Navigation.NavigateToLogin--but it doesn't work at all; it is simply ineffective.
I think this issue is still applicable: https://github.com/dotnet/aspnetcore/issues/40046#issuecomment-1042575825 - at least that's how I solved it. Not sure if there's a better way to do this.
So, step 1: You add class AuthExtensions:
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace Your.Namespace;
/// <summary>
/// https://github.com/dotnet/aspnetcore/issues/40046
/// </summary>
public static class AuthExtensions
{
/// <summary>
/// Adds support for Auth0 authentication for SPA applications using <see cref="Auth0OidcProviderOptions"/> and the <see cref="RemoteAuthenticationState"/>.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param>
/// <param name="configure">An action that will configure the <see cref="RemoteAuthenticationOptions{TProviderOptions}"/>.</param>
/// <returns>The <see cref="IServiceCollection"/> where the services were registered.</returns>
public static IRemoteAuthenticationBuilder<RemoteAuthenticationState, RemoteUserAccount> AddAuth0OidcAuthentication(this IServiceCollection services, Action<RemoteAuthenticationOptions<Auth0OidcProviderOptions>> configure)
{
services.TryAddEnumerable(ServiceDescriptor.Scoped<IPostConfigureOptions<RemoteAuthenticationOptions<Auth0OidcProviderOptions>>, DefaultAuth0OidcOptionsConfiguration>());
return services.AddRemoteAuthentication<RemoteAuthenticationState, RemoteUserAccount, Auth0OidcProviderOptions>(configure);
}
}
public class Auth0OidcProviderOptions : OidcProviderOptions
{
public MetadataSeed MetadataSeed { get; set; } = new();
}
public class MetadataSeed
{
[JsonPropertyName("end_session_endpoint")]
public string EndSessionEndpoint { get; set; } = null!;
}
// Copy/paste from Microsoft.AspNetCore.Components.WebAssembly.Authentication with the option type changed.
public class DefaultAuth0OidcOptionsConfiguration : IPostConfigureOptions<RemoteAuthenticationOptions<Auth0OidcProviderOptions>>
{
private readonly NavigationManager _navigationManager;
public DefaultAuth0OidcOptionsConfiguration(NavigationManager navigationManager) => _navigationManager = navigationManager;
public void Configure(RemoteAuthenticationOptions<Auth0OidcProviderOptions> options)
{
if (options == null)
{
return;
}
options.UserOptions.AuthenticationType ??= options.ProviderOptions.ClientId;
var redirectUri = options.ProviderOptions.RedirectUri;
if (redirectUri == null || !Uri.TryCreate(redirectUri, UriKind.Absolute, out _))
{
redirectUri ??= "authentication/login-callback";
options.ProviderOptions.RedirectUri = _navigationManager.ToAbsoluteUri(redirectUri).AbsoluteUri;
}
var logoutUri = options.ProviderOptions.PostLogoutRedirectUri;
if (logoutUri == null || !Uri.TryCreate(logoutUri, UriKind.Absolute, out _))
{
logoutUri ??= "authentication/logout-callback";
options.ProviderOptions.PostLogoutRedirectUri = _navigationManager.ToAbsoluteUri(logoutUri).AbsoluteUri;
}
}
public void PostConfigure(string name, RemoteAuthenticationOptions<Auth0OidcProviderOptions> options)
{
if (string.Equals(name, Options.DefaultName, StringComparison.Ordinal))
{
Configure(options);
}
}
}
Then in your program.cs you wire it up like this:
builder.Services.AddAuth0OidcAuthentication(options =>
{
var authority = builder.Configuration["GoogleAuth:Authority"];
var clientId = builder.Configuration["GoogleAuth:ClientId"];
options.ProviderOptions.MetadataSeed.EndSessionEndpoint = $"{authority}/v2/logout?client_id={clientId}&returnTo={builder.HostEnvironment.BaseAddress}";
// Allowing only MyDomain.Com users
options.ProviderOptions.AdditionalProviderParameters.Add("hd", builder.Configuration["GoogleAuth:hd"]);
});
Note that I'm not 100% sure which exact parameter you should be adding.
"hd" is the domain hint parameter for google cloud based domains: https://developers.google.com/identity/openid-connect/openid-connect#hd-param
Based on this guide: https://learn.microsoft.com/en-us/azure/active-directory-b2c/direct-signin?pivots=b2c-user-flow - It looks like the Azure domain hint parameter is either login_hint or domain_hint
From this page, I founds that I can create a InteractiveRequestOptions object, run options.TryAddAdditionalParameter("domainHint", "mydomain.com");, and pass that into Navigation.NavigateToLogin, and it works great. Just be careful to use domainHint and not domain_hint, contrary to several pieces of documentation.

.NET Core default dependency injection with Castle DynamicProxy

I have many AOP libraries that use Castle DynamicProxy with Autofac DI container for logging, auditing, transaction control, etc.
I wonder if there is a way to declare interceptors using the default .NET Core DI container. It will be good to have this flexibility since many .NET Core projects don't use Autofac.
Yes, you can use DynamicProxy using Core DI. I've written up a blog post explaining it at http://codethug.com/2021/03/17/Caching-with-Attributes-in-DotNet-Core5/, but here is the code for it:
Create an attribute
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class CacheAttribute : Attribute
{
public int Seconds { get; set; } = 30;
}
Create an interceptor (requires Castle.Core nuget package)
public class CacheInterceptor : IInterceptor
{
private IMemoryCache _memoryCache;
public CacheInterceptor(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
// Create a cache key using the name of the method and the values
// of its arguments so that if the same method is called with the
// same arguments in the future, we can find out if the results
// are cached or not
private static string GenerateCacheKey(string name,
object[] arguments)
{
if (arguments == null || arguments.Length == 0)
return name;
return name + "--" +
string.Join("--", arguments.Select(a =>
a == null ? "**NULL**" : a.ToString()).ToArray());
}
public void Intercept(IInvocation invocation)
{
var cacheAttribute = invocation.MethodInvocationTarget
.GetCustomAttributes(typeof(CacheAttribute), false)
.FirstOrDefault() as CacheAttribute;
// If the cache attribute is added ot this method, we
// need to intercept this call
if (cacheAttribute != null)
{
var cacheKey = GenerateCacheKey(invocation.Method.Name,
invocation.Arguments);
if (_memoryCache.TryGetValue(cacheKey, out object value))
{
// The results were already in the cache so return
// them from the cache instead of calling the
// underlying method
invocation.ReturnValue = value;
}
else
{
// Get the result the hard way by calling
// the underlying method
invocation.Proceed();
// Save the result in the cache
var options = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow =
new System.TimeSpan(hours: 0, minutes: 0,
seconds: cacheAttribute.Seconds)
};
_memoryCache.Set(cacheKey, invocation.ReturnValue,
options);
}
}
else
{
// We don't need to cache the results,
// nothing to see here
invocation.Proceed();
}
}
}
Add an extension method to help register classes in DI:
public static void AddProxiedScoped<TInterface, TImplementation>
(this IServiceCollection services)
where TInterface : class
where TImplementation : class, TInterface
{
// This registers the underlying class
services.AddScoped<TImplementation>();
services.AddScoped(typeof(TInterface), serviceProvider =>
{
// Get an instance of the Castle Proxy Generator
var proxyGenerator = serviceProvider
.GetRequiredService<ProxyGenerator>();
// Have DI build out an instance of the class that has methods
// you want to cache (this is a normal instance of that class
// without caching added)
var actual = serviceProvider
.GetRequiredService<TImplementation>();
// Find all of the interceptors that have been registered,
// including our caching interceptor. (you might later add a
// logging interceptor, etc.)
var interceptors = serviceProvider
.GetServices<IInterceptor>().ToArray();
// Have Castle Proxy build out a proxy object that implements
// your interface, but adds a caching layer on top of the
// actual implementation of the class. This proxy object is
// what will then get injected into the class that has a
// dependency on TInterface
return proxyGenerator.CreateInterfaceProxyWithTarget(
typeof(TInterface), actual, interceptors);
});
}
Add these lines to ConfigureServices in Startup.cs
// Setup Interception
services.AddSingleton(new ProxyGenerator());
services.AddScoped<IInterceptor, CacheInterceptor>(
After that, if you want to use the cache interceptor, you need to do two things:
First, add the attribute to your method
[Cache(Seconds = 30)]
public async Task<IEnumerable<Person>> GetPeopleByLastName(string lastName)
{
return SomeLongRunningProcess(lastName);
}
Second, register the class in DI using the Proxy/Interception:
services.AddProxiedScoped<IPersonRepository, PersonRepository>();
Instead of the normal way without the Proxy/Interception:
services.AddScoped<IPersonRepository, PersonRepository>();
The base .NET Core container does not have any extra features like interceptors. The whole reason the DI container in .NET Core can be swapped out for something like Autofac is so you can move to a different container once you outgrow the default one.

Windsor container: how to replace ISpecialService implementation at resolving time

I have several Windsor Installers at my ASP.NET MVC application. They register controllers and services. Most of them depend on ICurrentService.
Controller example:
public DataStructureController(
IMapper mapper,
DataEntityService dataEntityService,
FieldDefinitionService fieldDefinitionService,
CompanyService companyService,
ICurrentService currentService,
SelectListService selectListService,
EnumResourceService enumResourceService,
WebPreprocessService preprocessService)
: base(preprocessService)
{
// Initialise variables code here
}
Service example:
public DataEntityService(DataEntitySpec specification, ICurrentService currentService)
: base(specification)
{
// Initialise variables code here
}
In my test classes I have a method, that I call once in [TestInitialize] marked method, or on/many times in [TestMethod] marked methods:
private static ICurrentService MockCurrentUser(User user)
{
var currentUserSerivceMock = new Mock<ICurrentService>(MockBehavior.Strict);
currentUserSerivceMock.Setup(x => x.UserId).Returns(user.Id);
currentUserSerivceMock.Setup(x => x.CompanyId).Returns(user.CompanyProfile.Id);
return currentUserSerivceMock.Object;
}
I want to replace ICurrentService implementation when calling the container.Resolve<> method, because it depends on HttpContext, that isn't available when unit tests run. Is it possible and how do I do it with minimum code?
You can simply create a fake HttpContext:
HttpContext.Current = new HttpContext(
new HttpRequest(null, "http://tempuri.org", null),
new HttpResponse(null));
And then in your tests:
[SetUp]
public void SetUp()
{
HttpContext.Current = new HttpContext(
new HttpRequest(null, "http://tempuri.org", null),
new HttpResponse(null));
}
[TearDown]
public void TearDown()
{
HttpContext.Current = null;
}
*Reference: http://caioproiete.net/en/fake-mock-httpcontext-without-any-special-mocking-framework/
Register your implementation as a Fallback with Windsor. Then in your test register your mock instance. That or just build up a dedicated instance of the container for your test and register what you like.

Signalr & Nancyfx integration

My app flow is as follows (simplified for clarity):
User GETs a page from "/page1"
User performs actions on the page (adds text, clicks, etc..), while Signalr communicates this data to the server, which performs heavy calculations in the background, and the results of those are returned to the page (lets call those "X").
When the user is finished with the page, he clicks a link to "/page2", that is returned by Nancy. This page is built using a Model that is dependent on X.
So, how do I build that Model based on X? How can signalr write to the user session in a way that Nancy can pick up on?
(I'm looking for a "clean" way)
Pending formal integration of Signalr & Nancy, this is what I came with. Basically, I share an IOC container between the two, and use an object (singleton lifetime) that maps users to state.
How to share an IOC container using the built in TinyIOC:
Extend Signalr's DefaultDependencyResolver
public class TinyIoCDependencyResolver : DefaultDependencyResolver
{
private readonly TinyIoCContainer m_Container;
public TinyIoCDependencyResolver(TinyIoCContainer container)
{
m_Container = container;
}
public override object GetService(Type serviceType)
{
return m_Container.CanResolve(serviceType) ? m_Container.Resolve(serviceType) : base.GetService(serviceType);
}
public override IEnumerable<object> GetServices(Type serviceType)
{
var objects = m_Container.CanResolve(serviceType) ? m_Container.ResolveAll(serviceType) : new object[] { };
return objects.Concat(base.GetServices(serviceType));
}
}
Replace Signalr's default DependencyResolver with our new one
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
CookieBasedSessions.Enable(pipelines);
// Replace UserToStateMap with your class of choice
container.Register<IUserToStateMap, UserToStateMap>();
GlobalHost.DependencyResolver = new TinyIoCDependencyResolver(container);
RouteTable.Routes.MapHubs();
}
}
Add IUserToStateMap as a dependency in your hubs and Nancy modules
public class MyModule : NancyModule
{
public MyModule(IUserToStateMap userToStateMap)
{
Get["/"] = o =>
{
var userId = Session["userId"];
var state = userToStateMap[userId];
return state.Foo;
};
}
}
public class MyHub : Hub
{
private readonly IUserToStateMap m_UserToStateMap;
public MyHub(IUserToStateMap userToStateMap)
{
m_UserToStateMap = userToStateMap;
}
public string MySignalrMethod(string userId)
{
var state = userToStateMap[userId];
return state.Bar;
}
}
What I would really want, is a way to easily share state between the two based on the connection ID or something like that, but in the meantime this solution works for me.
Did you arrive hear looking for a simple example of how to integrate Nancy and SignalR? I know I did.
Try this question instead (I self-answered it).
SignalR plus NancyFX : A simple but well worked example

Managing NHibernate sessions for a multi-tenant ASP.NET application

I have an existing multi-tenant ASP.NET application where all users authenticate against a single SQL Server database. This database also contains several other settings type data that is used within the application. Each client after authentication, utilizes their own SQL Server database for data storage, for isolation purposes. Essentially all of the client database are identical and reside on the same server, but reside on one or more servers as well.
The application is currently written in asp.net 2.5 framework and utilizes the Microsoft Practices Enterprise Library for DAL, and we are looking to migrate to 4.0 and implement NHibernate to replace the MPEL.
I have implemented a solution already using NHibernate and the 4.0 framework, so I am familiar with the concepts. I found the resources for my current session manager here as a matter of fact. But that application only had a single database, so not much too it. The implementation is essentially what you see here:
http://www.lostechies.com/blogs/nelson_montalvo/archive/2007/03/30/simple-nhibernate-example-part-4-session-management.aspx
The other solutions that I have seen suggest multiple config entries and/or files to manage this, but that is not desirable, since we may add new clients frequently and all of the connection information is already maintained in the authentication database.
Does anyone have any suggestions on how I might be able to pass in the client's connection string to a session manager?
The following is my current session manager class, which is based on the article mentioned above.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cache;
using singlepoint.timeclock.domain;
namespace singlepoint.timeclock.repositories
{
/// <summary>
/// Handles creation and management of sessions and transactions. It is a singleton because
/// building the initial session factory is very expensive. Inspiration for this class came
/// from Chapter 8 of Hibernate in Action by Bauer and King. Although it is a sealed singleton
/// you can use TypeMock (http://www.typemock.com) for more flexible testing.
/// </summary>
public sealed class nHibernateSessionManager
{
private ISessionFactory idadSessionFactory;
private ISessionFactory clientSessionFactory;
private string _client;
#region Thread-safe, lazy Singleton
// lazy initialisation, therefore initialised to null
private static nHibernateSessionManager instance = null;
/// <summary>
/// This is a thread-safe, lazy singleton. See http://www.yoda.arachsys.com/csharp/singleton.html
/// for more details about its implementation.
/// </summary>
public static nHibernateSessionManager Instance
{
get { return GetInstance(); }
}
public static nHibernateSessionManager GetInstance()
{
// lazy init.
if (instance == null)
instance = new nHibernateSessionManager();
return instance;
} // GetInstance
/// <summary>
/// Initializes the NHibernate session factory upon instantiation.
/// </summary>
private nHibernateSessionManager()
{
InitSessionFactory();
}
/// <summary>
/// Initializes the NHibernate session factory upon instantiation.
/// </summary>
private nHibernateSessionManager(string client)
{
InitSessionFactory();
InitClientSessionFactory(client);
}
/// <summary>
/// Assists with ensuring thread-safe, lazy singleton
/// </summary>
private class Nested
{
static Nested()
{
}
internal static readonly nHibernateSessionManager nHibernatenHibernateSessionManager = new nHibernateSessionManager();
}
#endregion
private void InitSessionFactory()
{
var configuration = new Configuration();
configuration.Configure(System.Configuration.ConfigurationManager.AppSettings["IDAD_HBM"]);
configuration.AddAssembly(typeof(enterprise).Assembly);
idadSessionFactory = configuration.BuildSessionFactory();
}
private void InitClientSessionFactory(string client)
{
var configuration = new Configuration();
configuration.Configure(System.Configuration.ConfigurationManager.AppSettings["Client_IDAD_HBM"]);
configuration.SetProperty("connection.connection_string", client);
configuration.AddAssembly(typeof(enterprise).Assembly);
clientSessionFactory = configuration.BuildSessionFactory();
}
/// <summary>
/// Allows you to register an interceptor on a new session. This may not be called if there is already
/// an open session attached to the HttpContext. If you have an interceptor to be used, modify
/// the HttpModule to call this before calling BeginTransaction().
/// </summary>
public void RegisterInterceptor(IInterceptor interceptor)
{
ISession session = ThreadSession;
if (session != null && session.IsOpen)
{
throw new CacheException("You cannot register an interceptor once a session has already been opened");
}
GetSession(interceptor);
}
public ISession GetSession()
{
return GetSession(null);
}
/// <summary>
/// Gets a session with or without an interceptor. This method is not called directly; instead,
/// it gets invoked from other public methods.
/// </summary>
private ISession GetSession(IInterceptor interceptor)
{
ISession session = ThreadSession;
if (session == null)
{
if (interceptor != null)
{
session = idadSessionFactory.OpenSession(interceptor);
}
else
{
session = idadSessionFactory.OpenSession();
}
ThreadSession = session;
}
return session;
}
public void CloseSession()
{
ISession session = ThreadSession;
ThreadSession = null;
if (session != null && session.IsOpen)
{
session.Close();
}
}
public void BeginTransaction()
{
ITransaction transaction = ThreadTransaction;
if (transaction == null)
{
transaction = GetSession().BeginTransaction();
ThreadTransaction = transaction;
}
}
public void CommitTransaction()
{
ITransaction transaction = ThreadTransaction;
try
{
if (transaction != null && !transaction.WasCommitted && !transaction.WasRolledBack)
{
transaction.Commit();
ThreadTransaction = null;
}
}
catch (HibernateException ex)
{
RollbackTransaction();
throw ex;
}
}
public void RollbackTransaction()
{
ITransaction transaction = ThreadTransaction;
try
{
ThreadTransaction = null;
if (transaction != null && !transaction.WasCommitted && !transaction.WasRolledBack)
{
transaction.Rollback();
}
}
catch (HibernateException ex)
{
throw ex;
}
finally
{
CloseSession();
}
}
/// <summary>
/// If within a web context, this uses <see cref="HttpContext" /> instead of the WinForms
/// specific <see cref="CallContext" />. Discussion concerning this found at
/// http://forum.springframework.net/showthread.php?t=572.
/// </summary>
private ITransaction ThreadTransaction
{
get
{
if (IsInWebContext())
{
return (ITransaction)HttpContext.Current.Items[TRANSACTION_KEY];
}
else
{
return (ITransaction)CallContext.GetData(TRANSACTION_KEY);
}
}
set
{
if (IsInWebContext())
{
HttpContext.Current.Items[TRANSACTION_KEY] = value;
}
else
{
CallContext.SetData(TRANSACTION_KEY, value);
}
}
}
/// <summary>
/// If within a web context, this uses <see cref="HttpContext" /> instead of the WinForms
/// specific <see cref="CallContext" />. Discussion concerning this found at
/// http://forum.springframework.net/showthread.php?t=572.
/// </summary>
private ISession ThreadSession
{
get
{
if (IsInWebContext())
{
return (ISession)HttpContext.Current.Items[SESSION_KEY];
}
else
{
return (ISession)CallContext.GetData(SESSION_KEY);
}
}
set
{
if (IsInWebContext())
{
HttpContext.Current.Items[SESSION_KEY] = value;
}
else
{
CallContext.SetData(SESSION_KEY, value);
}
}
}
private static bool IsInWebContext()
{
return HttpContext.Current != null;
}
private const string TRANSACTION_KEY = "CONTEXT_TRANSACTION";
private const string SESSION_KEY = "CONTEXT_SESSION";
[Obsolete("only until we can fix the session issue globally")]
internal ISession OpenSession()
{
return idadSessionFactory.OpenSession();
}
}
}
This is being called from a repository class like so:
public string getByName(string name)
{
return getByName(nHibernateSessionManager.Instance.GetSession(), name);
}
What I would really like to be able to do is the following:
public string getByName(string name, string clientConnectionString)
{
return getByName(nHibernateSessionManager.Instance.GetSession(clientConnectionString), name);
}
But I am having trouble modifying my existing session manager to accomodate this.
You appear to be asking to swap a connection for a given session. Or rather that is certainly what the code you have written is asking - "return a session identified by the name parameter, and it should also now use the connection string provided by this method."
That is not possible. NHibernate builds a session (and actually really a session factory) per connection and once built the factory and session are immutable. You cannot change connections for an existing session.
I got the impression that your application involves mostly in initial connection string that is the moving target, but after that your "real" session is on a single database. If that is the case, NHibernate can easily do this. If that is not the case, well, some things NHibernate is just not that well suited for. Maybe understanding a little more about the basis NHibernate operates on is helpful either way?
One of my genuine criticisms of NHibernate is that you have a somewhat arcane use of terminology and the well known unhelpful nature of it's exception messages. These coupled with the fact that what it is doing is in reality mechanically complicated tends to really obscure that there is a relatively simple and technically sound underlying model.
In this case, if you think about it this business of an immutable session makes a lot of sense. NHibernate connects to a database, but it also maintains objects in the session so they can be persisted back to that database at a later time. NHibernate does not support changing connections per session because there may already be other objects in the session and if you change connections their persistence is no longer assured.
Now, what you can do is create a factory/session per database for multiple databases and access them in one application, but objects still belong to their own session. You can even move objects to a new session with a different connection. In this case you have what would logically be a "replication" scenario. NHibernate supports this but you have to do most of the work. This also makes sense - they really cannot give you that as stable out of the box functionality, you have to manage a process like that on your own.
You can also build code to do exactly what you are asking. But think about what that is. Make a session, not per database, but only for this specific instance of this specific repository. I am thinking that is most likely not really what you want. But that is exactly what the semantics of your request are saying to do. Your existing class, On the other hand, was built on different semantics which are more typically what people want - "Build a session for this particular connection definition, i.e this database."
A real need to inject a connection string at the repository level implies that now not only is the database a moving target, but at the actual table level the target also moves. If that is the case, NHibernate is possibly not a good option. If that is not the case, you may be trying to mix programming paradigms. NHiberate imposes a few what I would call "assumptions" rather than any sort of real "limitations" and in return you don't have to write a bunch of code that would allow you a finer grain of control because often you really don't need that additional control.
Sorry if this is no longer a direct answer to your question, hopefully it is helpful somehow.
Original Answer:
Sure, since the connection info is in the authentication database this is easy.
1) Configure NHibernate in the "usual" fashion and point the config at the authentication database. Get the db connection for the user, and then close that session and session factory. You are done with that one now.
2) Create a new session etc this time in code instead of a config file.
class MyNewSession
{
private ISession _session;
private ISessionFactory _factory;
public void InitializeSession()
{
NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
config.Properties.Clear();
IDictionary props = new Hashtable();
// Configure properties as needed, this is pretty minimal standard config here.
// Can read in properties from your own xml file or whatever.
// Just shown hardcoded here.
props["proxyfactory.factory_class"] = "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle";
props["connection.provider"] = "NHibernate.Connection.DriverConnectionProvider";
props["dialect"] = "NHibernate.Dialect.MsSql2000Dialect";
props["connection.driver_class"] = "NHibernate.Driver.SqlClientDriver";
props["connection.connection_string"] = "<YOUR CONNECTION STRING HERE>";
props["connection.isolation"] = "ReadCommitted";
foreach (DictionaryEntry de in props)
{
config.Properties.Add(de.Key.ToString(), de.Value.ToString());
}
// Everything from here on out is the standard NHibernate calls
// you already use.
// Load mappings etc, etc
// . . .
_factory = config.BuildSessionFactory();
_session = _factory.OpenSession();
}
}
I know this is old but if you have not found a solution I hope this will help,
I created a solution that uses multisessionfactory using unhaddins (I made alterations to suit my needs).
Basically the multisession factory creates session factories for each database and stores in Application object.
Depending on the client the call to getfactory("name of factory from factory config file") returns correct database to query on.
You will have to alter your management module to support this and all of your repositories to support the change in management. This may be impractical at first but you have to alter them anyway. Your calls from your repository can be something like this:
public string getByName(string name)
{
return getByName(nHibernateSessionManager.SessionFactoryManager.GetFactory(Session["session variable that holds client session factory name that was set on login"]).GetCurrentSession(), name);
}
or (creating a method in the sessionmanager to return session of a given factory) your code could be like this
public string getByName(string name)
{
return getByName(nHibernateSessionManager.GetSession(Session["session variable that holds client session factory name that was set on login"]), name);
}

Resources