The following is an example from a Windows service I am working on. This class is registered with castle as the implementation of the interface and it is instantiated ands called in the service container like this:
The class has dependencies on a repository and another service that both get taken care of by Castle. The interface simply defines the Poll() method. The UnitOfWork takes care of wrapping a transaction and closing the session at the end. The session will get re-opened the next time somebody uses it. Note that services should use ThreadSessionStorage from Contrib as defined in the docs. Here's the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Symbio.Printable.Core.DataInterfaces;
using SharpArchContrib.Core;
using log4net;
using Symbio.Printable.Core;
using SharpArchContrib.Castle.NHibernate;
namespace Symbio.Printable.ApplicationServices.Poller {
public class SymbioOrderCreatorPollingService : IPollerService {
private IOrderRepository orderRepository;
private ISymbioOrderCreatorService symbioOrderCreatorService;
private ILog logger = LogManager.GetLogger(typeof(SymbioOrderCreatorPollingService));
public SymbioOrderCreatorPollingService(IOrderRepository orderRepository, ISymbioOrderCreatorService symbioOrderCreatorService) {
ParameterCheck.ParameterRequired(orderRepository, "orderRepository");
ParameterCheck.ParameterRequired(symbioOrderCreatorService, "symbioOrderCreatorService");
this.orderRepository = orderRepository;
this.symbioOrderCreatorService = symbioOrderCreatorService;
}
public string DescriptiveName { get; set; }
[UnitOfWork]
public void Poll() {
logger.Info("Polling for order to send to Symbio");
var orders = orderRepository.GetOrdersToSendToSymbio();
logger.InfoFormat("There are {0} orders to send to Symbio", orders.Count());
foreach (var order in orders) {
var result = symbioOrderCreatorService.CreateSymbioOrder(polledOrder, order.PrintableInstance);
if (result.IsSuccess) {
logger.DebugFormat("Order {0} successfully created Symbio order {1}", order.PrintableOrderId, result.SymbioOrderId);
order.SymbioOrderId = result.SymbioOrderId;
order.UtcDateTimeSentToSymbio = DateTime.UtcNow;
order.ErrorMessage = null;
}
else {
order.ErrorMessage = result.ErrorMessage;
}
orderRepository.SaveOrUpdate(order);
}
}
}
}