Consider 'mixed' application that consists of couple asp.net web-form, several asp.net mvc controllers, fistful of web.api controller, a bit of web-enabled wcf services and ofcourse unit-tests. These are all 'input-points' that accept requests. Now consider each for each 'input-type' I have a call-chain that ends calling method of the following 'service':
class SomeService: IService // not Wcf or Web service, just BL
{
private readonly IDependency1 dependency1;
public SomeService(IDependency1 dependency1)
{
this.dependency1 = dependency1;
}
private Anything DoSomething()
{
var result1 = this.dependecy1.GetSomeData();
return DoSomeFancyCalculations(result1);
}
}
public interface IDependency1
{
string GetSomeData();
}
I register this service once on Application_Start method as 'per-dependency'. Nothing interesting. However now I want that IDependency returns different data based on the context:
- webform -> "<asp:Net_WebForm />"
- mvc -> '@{ asp.net = "mvc" }'
- webapi -> "ipabew"
- wcf -> '{ d: 'wcf' }'
- unit test -> 'Assert.False("i was not tested")'
For unit tests I can make separate single registration, but for other contexts decition should be made automagically. I can only think of using keyed services and additional factory that will detect current context and resolve dependency with appropriate key:
public static RequestContext DetectContext()
{
if (null != OperationContext.Current)
{
return RequestContext.Wcf;
}
...
}
builder.Register(
c =>
{
var context = DetectContext();
return c.ResolveKeyed<IDependency1>(context);
}
Is there any autofac magic that can do this? It would be nice if i could write smth like this:
builder
.RegisterType<WebFormDependency>()
.As<IDependency1>()
.ForWebForms()