Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using .with<T>(instance) #24

Closed
jlhorner1974 opened this issue Oct 20, 2017 · 2 comments
Closed

Using .with<T>(instance) #24

jlhorner1974 opened this issue Oct 20, 2017 · 2 comments

Comments

@jlhorner1974
Copy link

jlhorner1974 commented Oct 20, 2017

I'm trying to set up a call to .with() when registering a type with an existing instance of an object, following the sample on the Hypodermic github site, as shown below. The .with() executes without incident, but it does not wire up the dependency in the parent object, which is left empty. According to the docs, it seems this should work. Is there something I'm doing wrong?

class IFoo
{
public:
virtual void Bar() = 0;
};

class Foo : public IFoo
{
public:
virtual void Bar() override {};
};

class IBaz { };

class Baz : public IBaz
{
public:
Baz(std::shared_ptr foo) : m_pFoo(foo) {};
std::shared_ptr m_pFoo;
};

Hypodermic::ContainerBuilder builder;
auto foo = std::make_shared();
builder.registerType() .with(foo) .as();
builder.build();

auto pBaz = pContainer->resolve();

@ybainier
Copy link
Owner

Hi, your example do not compile, you are missing the template parameters.

Assuming you are trying to resolve Baz which should be injected a IFoo, and that you want to resolve Baz as a IBaz:

ContainerBuilder builder;

auto foo = std::make_shared< Foo >();

builder.registerType< Baz >()
           .with< IFoo >(foo)
           .as< IBaz >();

auto container = builder.build();

auto baz = container->resolve< IBaz >();

But you could write it that way too:

ContainerBuilder builder;

auto foo = std::make_shared< Foo >();

builder.registerInstance(foo).as< IFoo >();
builder.registerType< Baz >().as< IBaz >();

auto container = builder.build();

auto baz = container->resolve< IBaz >();

Is this solving your problem?

@jlhorner1974
Copy link
Author

jlhorner1974 commented Oct 20, 2017

Ah, I see now -- I did have the template types in my post, but I didn't mark the text as code, so they got stripped when I submitted the post.

I see my problem now, and I feel stupid. In my call to resolve(), I passed in Baz as the type instead of IBaz, so of course, it wasn't working.

I fixed my mistake and all works as it should. Thank you for your help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants