配置 WCF 依赖项
本文关键字:依赖 WCF 配置 | 更新日期: 2023-09-27 18:37:11
我正在尝试在Windows服务主机中托管我的WCF服务。为了管理依赖项,我正在使用城堡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;
}
}
}
我的服务一实现如下:
[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 传递给容器?我将如何配置它,以便在托管它时,它不会抱怨不让主机知道依赖项并不断查找和故障转移默认构造函数实现?
谢谢-话筒
您需要在
WCF ServiceHost 而不是 Windows 服务代码中启动 WCF 服务的 Windsor 容器。查看这两篇关于 Windows 服务中的 Castle WCF 设施和 WCF 的博客文章,了解您需要执行的操作。基本上,Windows 服务代码只是启动一个 WCF ServiceHostFactory,该工厂是从 Castle WCF 设施获得的,该工厂是实际配置 Castle 容器的工厂。