我想讓Castle Windsor DI與作爲Windows服務託管的WCF服務一起工作。我已經對這裏的方法DI與Windows服務中的Castle Windsor託管WCF服務
WCF Service Library hosted as a Windows Service using Castle.Windsor 3.0 issue
不過,我的問題是,如果我的服務實現類不具有默認參數的構造函數,ServiceHost的不會讓我在OnStart中創建的這個實例()。如果我提供一個無參數的構造函數,服務控制檯將使用該構造函數啓動服務,所以我沒有注入任何依賴項。
代碼如下
public class WindowsService : ServiceBase
{
public ServiceHost ServiceHost;
public WindowsService()
{
ServiceName = "CRMCustomerService";
}
public static void Main()
{
// Bootstrap the Castle Windsor DI setup
Run(CreateContainer().Resolve<ServiceBase>());
}
#region Service methods
protected override void OnStart(string[] args)
{
if (ServiceHost != null)
{
ServiceHost.Close();
}
ServiceHost = new ServiceHost(typeof(CustomerService));
ServiceHost.Open();
}
protected override void OnStop()
{
if (ServiceHost != null)
{
ServiceHost.Close();
ServiceHost = null;
}
}
#endregion
#region Private Methods
private static IWindsorContainer CreateContainer()
{
var container = new WindsorContainer();
container.Install(FromAssembly.This());
return container;
}
#endregion
}
[ServiceBehaviorAttribute(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Single)]
public class CustomerService : ICustomerService
{
private readonly IDataRepository _repository;
private readonly ILogger _logger;
public CustomerService(IDataRepository repository)
{
_repository = repository;
_logger = new RootLogger(Level.Error);
}
}
public class ServicesInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container
.AddFacility<WcfFacility>(f =>
{
f.CloseTimeout = TimeSpan.Zero;
})
.Register(
Component
.For<IDataRepository>()
.ImplementedBy<CustomerRepository>()
.LifeStyle.Transient
.AsWcfService(),
Component.For<ServiceBase>().ImplementedBy<WindowsService>());
}
}
有人能看到我在做什麼錯?我想在服務啓動時以及WCF服務的一個實例創建時引導Windsors DI容器,以便在此時注入依賴關係。