Accessing IHttpRequest or IRequestContext from container

I need dependency resolution for my services to be based on the HTTP header value in the incoming request.

I've tried registering the factory method like this:

container.Register(c => GetDependencyForRequest(c.Resolve<IHttpRequest>()));

      

and also i tried:

container.Register(c => GetDependencyForRequest(c.Resolve<IRequestContext>()));

      

However, both ResolutionException

s.

I would rather not seed my services by deciding which implementation to use. I just would like them to have IDependency

in their constructor and allow the container to resolve it.

Is there a way to do this? Or is there another way to do this?

+3


source to share


2 answers


The answer was much simpler than I thought:



container.Register(c => FindDependencyForRequest(HttpContext.Current.ToRequestContext()));

      

+1


source


I'm not sure if there is a way to do this through an IoC container. A possible solution would be to create your own service subclass that can "update" your independence in its constructor based on the Http header. Below is some pseudocode to give you an idea. Hope this helps.



public abstract class MyServiceBase : Service
{
    private Dictionary<string, Func<IDependency>> Dependencies = new Dictionary<string, Func<Dependency>>()
                                                                    {
                                                                        {"header1", () => new Dependency()},
                                                                        {"header2", () => new Dependency()}
                                                                    };

    public IDependency Dependency { get; set; }

    protected MyServiceBase()
    {
        this.Dependency = this.Dependencies[this.RequestContext.GetHeader("headerName")]();
    }
}

      

+2


source







All Articles