- NHibernate: How to inject dependency on an entity
- public class Employee
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public void SendNotification(string message, INotifier notifier)
- {
- notifier.SendMessage(string.Format("Message for customer '{0}' ({1}): {2}", Name, Id, message));
- }
- }
- public interface INotifier
- {
- void SendMessage(string message);
- }
- class EmailNotifier : INotifier
- {
- public void SendMessage(string message)
- {
- // SmtpClient...
- }
- }
- class SMSNotifier : INotifier
- {
- public void SendMessage(string message)
- {
- // SMS ...
- }
- }
- public class NotificationCommandHandler : ICommandHandler<NotificationCommand>
- {
- private readonly INotifier _notifier;
- public NotificationCommandHandler(INotifier notifier)
- {
- _notifier = notifier;
- }
- public void Execute(NotificationCommand commandMessage)
- {
- commandMessage.Employee.SendNotification(commandMessage.Message, _notifier);
- }
- }
- public class NotificationCommand
- {
- public string Message { get; set; }
- public Employee Employee { get; set; }
- }
- public class Controller
- {
- private readonly IMessageProcessor _messageProcessor;
- public Controller(IMessageProcessor messageProcessor)
- {
- _messageProcessor = messageProcessor;
- }
- public void SendNotification (Employee employee, string message)
- {
- var sendMailCommand = new NotificationCommand
- {
- Employee = employee,
- Message = message
- };
- _messageProcessor.Process(sendMailCommand);
- }
- }
- public class DependencyInjectionEntityInterceptor : EmptyInterceptor
- {
- IContainer _container;
- ISession _session;
- public DependencyInjectionEntityInterceptor(IContainer container)
- {
- _container = container;
- }
- public override void SetSession(ISession session)
- {
- _session = session;
- }
- public override object Instantiate(string clazz, EntityMode entityMode, object id)
- {
- if (entityMode == EntityMode.Poco)
- {
- var type = Assembly.GetAssembly(typeof (SomeClass)).GetTypes().FirstOrDefault(x => x.FullName == clazz);
- var hasParameters = type.GetConstructors().Any(x => x.GetParameters().Any());
- if (type != null && hasParameters)
- {
- var instance = _container.GetInstance(type);
- var md = _session.SessionFactory.GetClassMetadata(clazz);
- md.SetIdentifier(instance, id, entityMode);
- return instance;
- }
- }
- return base.Instantiate(clazz, entityMode, id);
- }
- }
- public FluentConfiguration GetFluentConfiguration(IContainer container)
- {
- return Fluently.Configure()
- .Database(MsSqlConfiguration.MsSql2008
- .ConnectionString(c => c.FromConnectionStringWithKey("Database"))
- .ShowSql())
- .Mappings(m =>
- m.AutoMappings.Add(AutoMap.AssemblyOf<SomeClass>()))
- .ExposeConfiguration(x =>
- x.SetInterceptor(new DependencyInjectionEntityInterceptor(container)));
- }