Submit to Reddit      
  

ChannelAdam WCF Library — Version 1 Documentation

Usage With Inversion of Control (IoC) Containers

It is easy to use the ServiceConsumerFactory from Inversion of Control (IoC) containers.

Below are examples with three popular IoC containers.

  1. AutoFac
  2. SimpleInjector
  3. Unity

Let's assume that there is the following class and we want to perform constructor injection with it.

public class ConstructorInjectedController
{
    public IServiceConsumer<IFakeService> FakeService { get; set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="ConstructorInjectedController"/> class.
    /// </summary>
    /// <param name="fakeService">The fake service.</param>
    public ConstructorInjectedController(IServiceConsumer<IFakeService> fakeService)
    {
        this.FakeService = fakeService;
    }
}

1. AutoFac

Here is how to use the ServiceConsumerFactory with AutoFac.

var builder = new Autofac.ContainerBuilder();
builder.Register(c => ServiceConsumerFactory.Create<IFakeService>("BasicHttpBinding_IFakeService")).InstancePerDependency();
builder.RegisterType<ConstructorInjectedController>();

var autofacContainer = builder.Build();

var controller = autofacContainer.Resolve<ConstructorInjectedController>();

2. SimpleInjector

Here is how to use the ServiceConsumerFactory with SimpleInjector.

var simpleInjectorContainer = new SimpleInjector.Container();
simpleInjectorContainer.Register(() => ServiceConsumerFactory.Create<IFakeService>("BasicHttpBinding_IFakeService"), SimpleInjector.Lifestyle.Transient);

var controller = simpleInjectorContainer.GetInstance<ConstructorInjectedController>();

3. Unity

And, here is how to use the ServiceConsumerFactory with Unity.

var unityContainer = new UnityContainer();

unityContainer
    .RegisterType<IServiceConsumer<IFakeService>>(
        new TransientLifetimeManager(),
        new InjectionFactory(c => ServiceConsumerFactory.Create<IFakeService>("BasicHttpBinding_IFakeService")))

    //
    // OR
    //
    //.RegisterType<IServiceConsumer<IFakeService>>(
    //    new InjectionFactory(c => ServiceConsumerFactory.Create<IFakeService>(() => new FakeServiceClient())))

    // 
    // OR more 'correctly'
    //
    //.RegisterType<IFakeService, FakeServiceClient>(new TransientLifetimeManager())
    //.RegisterType<IServiceConsumer<IFakeService>>(
    //    new InjectionFactory(c =>
    //        ServiceConsumerFactory.Create<IFakeService>(() => (ICommunicationObject)c.Resolve<IFakeService>())))
    ;

var controller = unityContainer.Resolve<ConstructorInjectedController>();


comments powered by Disqus