Skip to content

Instantly share code, notes, and snippets.

@stormoz
Last active August 29, 2015 13:57
Show Gist options
  • Save stormoz/9906381 to your computer and use it in GitHub Desktop.
Save stormoz/9906381 to your computer and use it in GitHub Desktop.
namespace AutofacResolveMultipleImplementations.BusinessLogic
{
using System;
public enum Service
{
Foo,
Bar
}
public interface IService
{
string Get();
}
public class FooService : IService
{
public string Get()
{
return "Foo";
}
}
public class BarService : IService
{
public string Get()
{
return "Bar";
}
}
public class FooServiceController
{
private readonly IService _service;
public FooServiceController(Func<Service, IService> service)
{
_service = service(Service.Foo);
}
public string Get()
{
return _service.Get();
}
}
public class BarServiceController
{
private readonly IService _service;
public BarServiceController(Func<Service, IService> service)
{
_service = service(Service.Bar);
}
public string Get()
{
return _service.Get();
}
}
}
namespace AutofacResolveMultipleImplementations.IoC
{
using System;
using Autofac; //Install-Package Autofac
using AutofacResolveMultipleImplementations.BusinessLogic;
public class IoC
{
private IContainer container;
public void Register()
{
var builder = new ContainerBuilder();
//Register controllers
builder.RegisterType<FooServiceController>().AsSelf();
builder.RegisterType<BarServiceController>().AsSelf();
//Register services
builder.RegisterType<FooService>().Keyed<IService>(Service.Foo);
builder.RegisterType<BarService>().Keyed<IService>(Service.Bar);
//Register factory to resolve services
builder.Register<Func<Service, IService>>(c => s => c.ResolveKeyed<IService>(s));
container = builder.Build();
}
public T Resolve<T>()
{
return container.Resolve<T>();
}
public void Release()
{
container.Dispose();
}
}
}
namespace Tests
{
using NUnit.Framework; //Install-Package NUnit
using AutofacResolveMultipleImplementations.BusinessLogic;
using AutofacResolveMultipleImplementations.IoC;
public class IoCTests
{
private readonly IoC _ioc;
public IoCTests()
{
_ioc = new IoC();
_ioc.Register();
}
[Test]
public void CanResolveFooController()
{
var fooBarClient = _ioc.Resolve<FooServiceController>();
var actual = fooBarClient.Get();
Assert.AreEqual("Foo", actual);
}
[Test]
public void CanResolveBarController()
{
var fooBarClient = _ioc.Resolve<BarServiceController>();
var actual = fooBarClient.Get();
Assert.AreEqual("Bar", actual);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment