Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 924
rossipedia Avatar asked Dec 05 '25 08:12

rossipedia


1 Answers

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")]();
    }
}
like image 129
paaschpa Avatar answered Dec 09 '25 19:12

paaschpa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!