Yesterday I showed the AuditInterceptor we are using in one of my applications. Maybe you noticed that we were using dependency injection:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NHibernateInterceptor : NHib.EmptyInterceptor | |
{ | |
private readonly ILogger _logger; | |
private readonly IUserFactory _userFactory; | |
public NHibernateInterceptor(ILogger logger, IUserFactory userFactory) | |
{ | |
_logger= logger; | |
_userFactory = userFactory; | |
} | |
} |
Important to notice is that we are injecting a scoped dependency that contains the current user id(through the IUserFactory).
The trick to get this working is to set the interceptor when the session is created.
Therefore we register our IInterceptor implementation in the IoC container(Autofac in our situation):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public override void Initialize(ContainerBuilder container) | |
{ | |
container.RegisterType<NHibernateUnitOfWorkFactory>().As<IUnitOfWorkFactory>(); | |
//Scoped registration helps us guarantee that we have the correct user for a request context | |
container.RegisterType<NHibernateInterceptor>().As<IInterceptor>().InstancePerLifetimeScope(); | |
} |
Then when we construct a new session instance we’ll get the IInterceptor from the container and link it to the session:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NHibernateUnitOfWorkFactory : IUnitOfWorkFactory | |
{ | |
private readonly IInterceptor _interceptor; | |
private readonly ISessionFactory _sessionFactory; | |
public NHibernateUnitOfWorkFactory(ISessionFactory sessionFactory, NHib.IInterceptor interceptor) | |
{ | |
_sessionFactory=sessionFactory; | |
_interceptor = interceptor; | |
} | |
public IUnitOfWork Create() | |
{ | |
var sessionFactory = _sessionFactory.Create(); | |
var session = sessionFactory | |
.WithOptions() | |
.Interceptor(_interceptor) | |
.OpenSession(); | |
return new UnitOfWork(session); | |
} | |
} |