使用autofac注册WCF客户端通道

时间:2014-09-26 08:49:36

标签: c# wcf autofac channelfactory

我想在autofac中注册WCF客户端通道,所以我可以通过在构造函数中包含服务契约接口来解决它们,例如像这样:

   public LoginFormController(ILoginService loginService)
   { ...

我有一个为我创建频道的工厂,只有一个公共通用方法:

public T GetChannel<T>()

我注册了我的工厂:

Builder.RegisterType<ClientChannelManager>().As<IClientChannelManager>();

我无法弄清楚是否有注册我的客户端频道的语法。这有效,但它不是我想要的:

Builder.Register(c => new ClientChannelManager(new SettingsProvider()).GetChannel<ILoginService>()).As<ILoginService>();

我希望从容器中解析出来,而不是创建ClientChannelManager的新实例及其构造函数参数。

我提出的最好的是我工厂中的静态GetChannel方法,该方法明确地从容器中解析实例:

    public static T ResolveChannel<T>(IComponentContext context)
    {
        IClientChannelManager manager = context.Resolve<IClientChannelManager>();
        return manager.GetChannel<T>();
    }

通过调用静态方法注册服务合同:

Builder.Register(c => ClientChannelManager.ResolveChannel<ILoginService>(c)).As<ILoginService>();

任何人都知道更优雅的语法/解决方案吗?

1 个答案:

答案 0 :(得分:1)

有一篇关于在Autofac维基上使用Autofac注册和使用WCF服务的文章,它准确显示了您的要求:http://docs.autofac.org/en/latest/integration/wcf.html