serg serg - 3 months ago 10
ASP.NET (C#) Question

Register Type wich is based on Request cookie

I'm using Autofac and my types registration looks like:

public class Global : HttpApplication, IContainerProviderAccessor
{
static IContainerProvider _containerProvider;
public IContainerProvider ContainerProvider { get { return _containerProvider; }}

protected void Application_Start(object sender, EventArgs e)
{

var builder = new ContainerBuilder();
var myCookie = Request.Cookies["MyTestCookie"];

if (myCookie != null)
builder.RegisterType<FirstService>().As<IService>().InstancePerRequest();
else
builder.RegisterType<SecondService>().As<IService>().InstancePerRequest();

_containerProvider = new ContainerProvider(builder.Build());
}
}


But it gives an error saying "Request is not available in this context". Can I register my types in another way to be able to use information from
Request
before?

Answer

Application_Start is called once while the application start and the autofac container is build for the global application, you would not want to register a service based on one Request here.

In order to do what you want, you can register both service as named service and add a third registration which resolve the correct named registration based on the cookie value. ie :

builder.RegisterType<FirstService>().Named<IService>("first").InstancePerRequest();
builder.RegisterType<SecondService>().Named<IService>("second").InstancePerRequest();


builder.Register(c => {
    var myCookie = HttpContext.Current.Request.Cookies["MyTestCookie"];

    if (myCookie != null)
        return c.ResolveNamed<IService>("first"); 
    else
        return c.ResolveNamed<IService>("second"); 
}).InstancePerRequest(); 
Comments