Autofac WCF集成 - 根据请求数据解析依赖关系

xda*_*sie 3 c# wcf autofac

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

例如,鉴于此数据合同......

[DataContract]
public class MyRequest
{
    [DataMember]
    public bool MyBool { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这个WCF服务......

public class MyWcfService : IWcfService
{
    private IService m_service;

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

    public virtual MyResponse Operation(MyRequest request) { }
}
Run Code Online (Sandbox Code Playgroud)

和这些依赖...

public interface IService { }
public class TypeA : IService { }
public class TypeB : IService { }
Run Code Online (Sandbox Code Playgroud)

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

约束:

  • 避免使用Autofac.Extras.Multitenant包是一个优点.
  • 还希望保持服务构造函数的签名不变.(见下面的答案)

Ale*_*tin 5

有几种方法可以实现这一目标.其中一种方法是使用IIndex<K,V>.它是内置的"查找"功能,可在基于密钥的服务实现之间进行选择.您可以在Autofac的维基页面上找到更多信息.示例代码可能如下所示:

// 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];
    }
}
Run Code Online (Sandbox Code Playgroud)

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