Search code examples
c#wcfautofacchannelfactory

Registering WCF client channels with autofac


I want to register WCF client channels in autofac, so I can resolve them simply by including the service contract interface in the constructor, e.g. like this:

   public LoginFormController(ILoginService loginService)
   { ...

I have a factory that creates the channels for me, with a single public generic method:

public T GetChannel<T>()

I register my factory:

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

I can't figure out if there is a syntax to register my client channel. This works, but its not what I want:

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

Instead of creating new instance of ClientChannelManager and its constructor arguments, I want it resolved from the container.

The best I have come up with is a static GetChannel method in my factory that resolves an instance from the container explicitly:

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

And register the service contract with a call to the static method:

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

Anyone know a more elegant syntax/solution for this?


Solution

  • There is a whole article on registering and consuming WCF services using Autofac on the Autofac wiki that shows exactly what you're asking for: http://docs.autofac.org/en/latest/integration/wcf.html