My web app has some slight variations in business logic and presentation logic depending on the type of user that is logged in. It seems like getting variations by injecting different concrete classes based on the user type is a good fit for DI. So I'm wondering what features of StructureMap I should use to achieve this (or if I'm way off base on the purposes of DI).
(I just learned that Profiles are not the way to accomplish this because setting the Profile isn't a per-thread operation: http://stackoverflow.com/questions/1494937/are-structuremap-profiles-thread-safe)
EDIT
Is this the way to go about this?
public class HomeController
{
private ISomeDependancy _someDependancy;
public HomeController(ISomeDependancy someDependancy)
{
_someDependancy = someDependancy;
}
public string GetNameFromDependancy()
{
return _someDependancy.GetName();
}
}
public interface ISomeDependancy
{
string GetName();
}
public class VersionASomeDependancy : ISomeDependancy
{
public string GetName()
{
return "My Name is Version A";
}
}
public class VersionBSomeDependancy : ISomeDependancy
{
public string GetName()
{
return "My Name is Version B";
}
}
public class VersionARegistry : Registry
{
public VersionARegistry()
{
// build up complex graph here
ForRequestedType<ISomeDependancy>().TheDefaultIsConcreteType<VersionASomeDependancy>();
}
}
public class VersionBRegistry : Registry
{
public VersionBRegistry()
{
// build up complex graph here
ForRequestedType<ISomeDependancy>().TheDefaultIsConcreteType<VersionBSomeDependancy>();
}
}
public class ContainerA : Container
{
public ContainerA()
: base(new VersionARegistry())
{
}
}
public class ContainerB : Container
{
public ContainerB()
: base(new VersionBRegistry())
{
}
}
[TestFixture]
public class Harness
{
[Test]
public void ensure_that_versions_load_based_on_named_containers()
{
ObjectFactory.Initialize(c =>
{
c.ForRequestedType<IContainer>().AddInstances(
x =>
{
x.OfConcreteType<ContainerA>().WithName("VersionA");
x.OfConcreteType<ContainerB>().WithName("VersionB");
}).CacheBy(InstanceScope.Singleton);
});
HomeController controller;
IContainer containerForVersionA = ObjectFactory.GetNamedInstance<IContainer>("VersionA");
controller = containerForVersionA.GetInstance<HomeController>();
Assert.That(controller.GetNameFromDependancy(), Is.EqualTo("My Name is Version A"));
IContainer containerForVersionB = ObjectFactory.GetNamedInstance<IContainer>("VersionB");
controller = containerForVersionB.GetInstance<HomeController>();
Assert.That(controller.GetNameFromDependancy(), Is.EqualTo("My Name is Version B"));
}
}