在WCF中使用Castle Windsor解析泛型
本文关键字:Windsor 泛型 Castle WCF | 更新日期: 2023-09-27 17:59:14
我花了一些时间来进行以下设计,并希望得到一些反馈-我正在使用Windsor来属性注入一个供Wcf服务使用的类型。
我的界面最初看起来是这样的,其中响应和请求类型是抽象的:
public interface IFooHandler
{
CheckFooResponse CheckFoo(CheckFooRequest request);
}
我担心我无法控制在实现IFooHandler的类中使用抽象类的哪些实现,所以设计改为:
SO问题1
public interface ICheckFooHandler<TRequest, TResponse>
where TRequest : CheckFooRequest where TResponse : CheckFooResponse
{
TResponse CheckFoo(TRequest request);
}
和用法:
public class CheckFooHandler : ICheckFooHandler<MyFooRequest, MyFooResponse>
{
MyFooResponse CheckFoo(MyFooRequest request) { ... }
}
然后我试着连接温莎:
IoCContainer = new WindsorContainer();
IoCContainer.Register
(Component
.For(typeof(ICheckFooHandler<,>))
.ImplementedBy(typeof(CheckFooHandler<,>)));
直到我将CheckFooHandler的实现更改为:,我才开始工作
SO问题2
public class CheckFooHandler<TRequest, TResponse> : ICheckFooHandler<TRequest, TResponse>
where TRequest : MyCheckFooRequest
where TResponse : MyCheckFooResponse, new()
{
public TResponse CheckFoo(TRequest request)
{
...
var response = new TResponse();
response.MyResponseProperty = "baz";
}
其实现通用接口契约,同时允许Windsor的通用语法工作。
在我的Wcf服务中,我有以下私人财产,由温莎注入:
private ICheckFooHandler<MyCheckFooRequest, MyCheckFooResponse> _checkFooHandler;
private ICheckFooHandler<MyCheckFooRequest, MyCheckFooResponse> CheckFooHandler
{
get
{
if (_checkFooHandler == null)
{
_checkFooHandler = Global.IoCContainer
.Resolve<ICheckFooHandler<MyFooRequest, MyFooResponse>>();
}
}
}
这个设计让我在处理程序中编译时间安全性,并允许我根据前面的问题使用IoC。
我的主要问题是必须使用具体的MyFoo类型,而不是Resolve<>中的抽象类型(),Property&字段签名。我希望能够指定一次混凝土类型,然后让温莎来做剩下的。
最后,我从未使用过new()泛型约束,我的用法在具体的CheckFoo()中有效吗?
您没有提供Wcf服务的设置信息,因此假设您没有使用Castle Windsor。
您可以使用Wcf设施通过Castle Windsor容器完全设置应用程序运行时和it Wcf服务。
示例:
container.AddFacility<WcfFacility>();
foreach (var wcfType in types.Where(t => t.IsInterface == false && t.IsAbstract == false)) // types should be coming from AppDomain.Current assemblies
{
foreach (var anInterface in wcfType.GetInterfaces().Where(anInterface => anInterface
.GetCustomAttributes(typeof(ServiceContractAttribute), true).Any()))
{
var serviceModel = new DefaultServiceModel().Hosted();
container.Register(Component.For(anInterface)
.ImplementedBy(wcfType)
.AsWcfService(serviceModel)
);
}
}
它将注册可用的WCF服务。然后,您应该能够直接在WCF服务的构造函数中依赖于类型化的依赖项。