gpt4 book ai didi

c# - Autofac WCF Integration - 根据请求数据解决依赖关系

转载 作者:行者123 更新时间:2023-11-30 14:31:06 24 4
gpt4 key购买 nike

我如何配置 Autofac 容器,以便它根据操作参数(请求对象)的属性值解析 WCF 服务的依赖关系?

例如,给定此数据契约(Contract)...

[DataContract]
public class MyRequest
{
[DataMember]
public bool MyBool { get; set; }
}

此 WCF 服务...

public class MyWcfService : IWcfService
{
private IService m_service;

public MyWcfService(IService service)
{
m_service = service;
}

public virtual MyResponse Operation(MyRequest request) { }
}

和这些依赖...

public interface IService { }
public class TypeA : IService { }
public class TypeB : IService { }

如果 MyBool 等于 true,我希望容器解析 TypeA,否则解析 TypeB。该功能可用吗?我应该以不同的方式处理问题吗?

约束:

  • 避免使用 Autofac.Extras.Multitenant 包会更好。
  • 也希望保持服务构造函数的签名不变。 (请参阅下面我的回答)

最佳答案

有几种方法可以实现这一点。其中一种方法是使用 IIndex<K,V> .它是内置的“查找”功能,可根据键在服务实现之间进行选择。您可以在 Autofac 的 wiki page 上找到更多信息.示例代码可能如下所示:

// Register your dependency with a key, for example a bool flag
builder.RegisterType<TypeA>().Keyed<IService>(true);
builder.RegisterType<TypeB>().Keyed<IService>(false);

// Your service could look like:
public class MyWcfService
{
private readonly IIndex<bool, IService> _services;

// Inject IIndex<Key,Value> into the constructor, Autofac will handle it automatically
public MyWcfService(IIndex<bool, IService> services)
{
_services = services;
}

public virtual void Operation(MyRequest request)
{
// Get the service that you need by the key
var service = _services[request.MyBool];
}
}

另一种方法是使用元数据功能。有关 wiki page 的更多信息.

关于c# - Autofac WCF Integration - 根据请求数据解决依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21243931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com