I want to have StructureMap return a Special Case called "None" for a certain instance.
Say I Have this class MyUser
which is scoped as HttpContext. I want to have a nested, dreived class None
(ie. MyUser.None
) which is returtned for the type MyUser
when there is no HttpContext
(for example, like in bootstrapping, Application_Start()
etc).
This would mean that certain calls could check for the Special Case type instead of null (more readable) like
if(value is MyUser.None)
// do special case things
else
// do normal case things
What SM config do I need to achieve this? I have tried the ConditionallyUse
method without much success. I keep getting NullReferenceExceptionS
throwing from within SM itself.
Turns out I had underlying SM configuration issues.
I am using the ConditionallyUse
method still however:
For<User>().ConditionallyUse(config =>
{
config.If(ctx => ctx.GetInstance<HttpContextBase>().User == null)
.ThenIt.Is.Type<User.None>();
config.TheDefault.Is.Type<User>();
});
I had to be more careful about NullReferenceExceptionS
from within SM - my underlying cause it seems was a scoping issue.. specifically how I was wanting to access a HttpContext
scoped instance in a test. I'm now using the HybridHttpOrThreadLocalScoped()
config and being more careful by using TryGetInstance()
where appropiate instead of GetInstance()
.