Wednesday, March 8, 2017

Autofac : resolve dependency per request based on parameter passed on HTTPHeader


Get the HTTP Context base

  builder.RegisterHttpRequestMessage(GlobalConfiguration.Configuration);

            builder.Register<HttpContextBase>(c =>
            {
                var context = (HttpContext.Current != null) ?
                new HttpContextWrapper(HttpContext.Current) :
                c.Resolve<System.Net.Http.HttpRequestMessage>().Properties["MS_HttpContext"] as HttpContextWrapper;
                return context;

            }).InstancePerRequest();

Resolve the dependency based on the request header value

  builder.Register(c =>
            {
                var route = c.Resolve<HttpContextBase>().Request.Headers.Get("provider");
                if (route == null)
                {
                    throw new ArgumentNullException($"A route must be specified");
                }
                return c.ResolveNamed<IInterfaceName>(route);
            }).InstancePerRequest();


No comments:

Featured post

How to connect to Mongo Atlas from Robo 3T

If you use a local instance of MongoDB, you might be a great fan of Robo3T. However, if you are using Mongo Atlas, the Atlas web interface p...

Popular Posts