Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpecFlow IObjectContainer: How to register and consume multiple objects of the same type?

Here is my Hooks class in SpecFlow.

 public sealed class Hooks
    {
        private readonly IObjectContainer _objectContainer;

        public ConcurApiHooks(IObjectContainer objectContainer)
        {
            _objectContainer = objectContainer;
        }

        [BeforeScenario]
        public void BeforeScenario()
        {   
            var httpClient1 = new HttpClient();
            var httpClient2 = new HttpClient();

            _objectContainer.RegisterInstanceAs(httpClient1, "client1");
            _objectContainer.RegisterInstanceAs(httpClient2, "client2");
        }

        [AfterScenario]
        public void AfterScenario()
        {
            //TODO: implement logic that has to run after executing each scenario
        }
    }

I am wanting to register two HttpClients because they will contain different base endpoints, authentication, etc. Up until this point this is all valid and SpecFlow allows for it.

Where I cannot seem to get this to work is on the consumption of it in my Steps class.

    [Binding]
    public sealed class ApiSteps : Steps
    {
        public ConcurApiSteps(HttpClient httpClient1, HttpClient httpClient2)
        {

        }
    }

Is there a way to do this? I would think so due to you being able to name the instance you register, but I cannot seem to get this to work.

like image 249
JCisar Avatar asked Sep 17 '25 08:09

JCisar


1 Answers

You can register like this

_objectContainer.RegisterInstanceAs<HttpClient>(new HttpClient(), "httpClient1");
_objectContainer.RegisterInstanceAs<HttpClient>(new HttpClient(), "httpClient2");

then in the constructor of another class

public Constrcutor(ObjectContainer objectContainer)
{
    var http1 = objectContainer.Resolve<HttpClient>("httpClient1");
    var http2 = objectContainer.Resolve<HttpClient>("httpClient2");
}
like image 159
u1234 Avatar answered Sep 19 '25 23:09

u1234



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!