I have implemented NHibernate custom context (ICurrentSessionContext). In this context I inject the NHibernate session so I have Session per call pattern setup. Ok, now I have made an interceptor that takes userId of the current logged user. Now I do this:
public ISession CurrentSession()
{
// Get the WCF InstanceContext:
var contextManager = OperationContext.Current.InstanceContext.Extensions.Find<NHibernateContextManager>();
if (contextManager == null)
{
throw new InvalidOperationException(
@"There is no context manager available.
Check whether the NHibernateContextManager is added as InstanceContext extension.
Make sure the service is being created with the NhServiceHostFactory.
This Session Provider is intended only for WCF services.");
}
var session = contextManager.Session;
AuditLogInterceptor interceptor = new AuditLogInterceptor();
if (session == null)
{
session = this._factory.OpenSession(interceptor);
interceptor.Session = session;
contextManager.Session = session;
}
return contextManager.Session;
}
My AuditLogInterceptor takes UserId but I don't know how (from where) to get this userId.
If your user is authenticated you can use:
OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With