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

Conditional constructor parameter injection #484

Closed
bounav opened this issue May 2, 2019 · 2 comments
Closed

Conditional constructor parameter injection #484

bounav opened this issue May 2, 2019 · 2 comments

Comments

@bounav
Copy link

bounav commented May 2, 2019

Hello,

I'd like to be able to register callback that lets me do some checks on the type being resolved before resolving a constructor dependency.

Something very similar to property injection on existing instance.

As well as having the factory available in the registration's lambda callback, it would be super useful to know the type of the class of which the constructor is being resolved.

public class HelloWorld
{
    public HelloWord(IFoo foo)
    {
        ...
    }
}

registry.Register<IFoo>((factory, serviceType) =>
     {
          return serviceType.Namespace.Contains("Blahblah") 
              ? factory.GetInstance<Foo>()
              : factory.GetInstance<Bar>();
     }

At the moment it seems the only way to achieve this is using an initializer?

PS: Did I mention I'd like to do all this with property injection disabled?

@seesharper
Copy link
Owner

seesharper commented May 2, 2019

You can check out the RegisterConstructorDependency method . It passes the parameter for which the dependency is being injected.
Check out this blog post that I wrote about logging a while back. It uses the RegisterConstructordependency to provide loggers that are tied to the services that the loggers are being injected into to.
http://www.lightinject.net/webapirequestlogging/

@bounav
Copy link
Author

bounav commented May 7, 2019

Thanks! I can't believe I missed it in the documentation.

The RegisterConstructordependency method is indeed just what I'm looking for.

The namespace of the declaring type (e.g. HelloWorld in my original example) is accessible via the ParameterInfo:

if (parameterInfo.Member.DeclaringType.Namespace.Contains("Blahblah"))
{
   ...
}

I'll close this issue now.
Thanks again for pointing me in the right direction (once more)!

@bounav bounav closed this as completed May 7, 2019
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