我试图让 Castle Windsor DI 与作为 Windows 服务托管的 WCF 服务一起工作。我已经采用了这里的方法
使用 Castle.Windsor 3.0 问题作为 Windows 服务托管的 WCF 服务库
但是我遇到的问题是,如果我的服务实现类没有默认的无参数构造函数,ServiceHost 将不允许我在 OnStart() 中创建 this 的实例。如果我提供无参数构造函数,服务控制台会使用该构造函数启动服务,因此我不会注入任何依赖项。
下面的代码
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 容器,以便在该点注入依赖项。