serg serg - 1 year ago 66
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)

_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

Answer Source

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.Register(c => {
    var myCookie = HttpContext.Current.Request.Cookies["MyTestCookie"];

    if (myCookie != null)
        return c.ResolveNamed<IService>("first"); 
        return c.ResolveNamed<IService>("second"); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download