我正在尝试在Windows服务主机中托管我的WCF服务。为了管理依赖关系,我正在使用Castle WCF工具。
这就是我的ContainerConfiguration(BootStrapper)的样子:
public class ConfigureContainer : IConfigureContainer
{
private const string ServiceOne= "ServiceOne";
private const string ServiceTwo = "ServiceTwo";
private const string ServiceThree = "ServiceThree";
private const string CurrentAssembly = "MyAssembly";
private readonly IWindsorContainer container;
public ConfigureContainer(IWindsorContainer container)
{
this.container = container;
}
public IWindsorContainer WindsorContainer { get { return container; } }
public void AndRegisterComponents()
{
container.Register(AllTypes.FromAssemblyNamed(CurrentAssembly)
.Pick().If(type => type.GetInterfaces().Any(i => i.IsDefined(typeof(ServiceContractAttribute), true)))
.Configure(configurer => configurer
.Named(configurer.Implementation.Name)
.AsWcfService(
new DefaultServiceModel()
.AddEndpoints(
WcfEndpoint.FromConfiguration(ServiceOne),
WcfEndpoint.FromConfiguration(ServiceTwo),
WcfEndpoint.FromConfiguration(ServiceThree))
.PublishMetadata()))
.WithService.Select((type, baseTypes) => type.GetInterfaces()
.Where(i => i.IsDefined(typeof(ServiceContractAttribute), true))));
}
}
这就是我在服务主机中进行托管的方式:
partial class DataServicesHost : ServiceBase
{
private IWindsorContainer windsorContainer;
public DataServicesHost()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
var configure = new ConfigureContainer();
windsorContainer = configure.WindsorContainer;
}
protected override void OnStop()
{
if(windsorContainer != null)
{
windsorContainer.Dispose();
windsorContainer = null;
}
}
}
我的ServiceOne实现如下:
[ServiceContract]
internal interface IServiceOne
{
[OperationContract]
void DoSomething();
}
public class ServiceOne : IServiceOne
{
private readonly IDependency dependency;
public ServiceOne(IDependency dependency)
{
this.dependency = dependency;
}
public void DoSomething()
{
dependency.GetSomething();
//do something
}
}
public interface IDependency
{
void GetSomething();
}
public class Dependency : IDependency
{
public void GetSomething()
{
//GetSomeThing
}
}
现在我的问题是:如何将IDependency传递给容器?我如何配置它,以便在托管它时,它不会抱怨不让主机知道依赖关系并继续查看和失败的默认构造函数实现?
谢谢, -Mike
答案 0 :(得分:1)
您需要在 WCF ServiceHost 内为WCF服务启动Windsor容器,而不是Windows服务代码。查看Castle WCF facility和WCF in a Windows Service上的这两篇博文,了解您需要做什么。基本上,Windows服务代码只是旋转了从Castle WCF工具获得的WCF ServiceHostFactory,而该工厂实际上配置了Castle容器。