我正在尝试在 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 传递给容器?我将如何配置它,以便在托管它时,它不会抱怨不让主机知道依赖关系并继续查找和故障转移默认构造函数实现?
谢谢,-迈克