Skip to content

Instantly share code, notes, and snippets.

@StacyGay
Created July 12, 2014 20:58
Show Gist options
  • Save StacyGay/3a5fd9ae6c6d217deb4f to your computer and use it in GitHub Desktop.
Save StacyGay/3a5fd9ae6c6d217deb4f to your computer and use it in GitHub Desktop.
DI Conditional Registration
public interface IBusinessLogicService
{
int DoSomething(int x);
}
public class MainLogicService : IBusinessLogicService
{
public int DoSomething(int x)
{
return 1 + x;
}
}
public class AltLogicService : IBusinessLogicService
{
public int DoSomething(int x)
{
return 1 - x;
}
}
public class Doer
{
private readonly IBusinessLogicService _logicService;
public Doer(IBusinessLogicService logicService)
{
_logicService = logicService;
}
public int DoIt(int x)
{
return _logicService.DoSomething(x);
}
}
public class Context
{
private const int Config = 1;
public void Main()
{
var container = new UnityContainer();
if (Config == 1)
container.RegisterType<IBusinessLogicService, MainLogicService>();
else
container.RegisterType<IBusinessLogicService, AltLogicService>();
var doer = container.Resolve<Doer>();
var result = doer.DoIt(2);
Console.WriteLine(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment