rossipedia
rossipedia

Reputation: 59367

Accessing IHttpRequest or IRequestContext from container

I need to have the resolution of a dependency for my services to be based off the value of an HTTP header in the incoming request.

I've tried registering a factory method like so:

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

and also I've tried:

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

However, both throw ResolutionExceptions.

I'd prefer not to have to saddle my Services with deciding which implementation to use. I'd just like them to have an IDependency in their constructor and let the container resolve it.

Is there some way to do this? Or is there another way to go about this?

Upvotes: 3

Views: 600

Answers (2)

rossipedia
rossipedia

Reputation: 59367

The answer was much simpler than I thought:

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

Upvotes: 1

paaschpa
paaschpa

Reputation: 4816

I'm not sure if there is a way to do it via an IoC container. A possible solution would be to create your own subclass of Service that can 'new up' your IDependency in its constructor based on the Http Header. Below is some psuedocode 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")]();
    }
}

Upvotes: 2

Related Questions