2

Given That

Component.For<IService>().ImplementedBy<SecretService>().Named("secretService")
Component.For<IService>().ImplementedBy<PublicService>().Named("publicService")

And

class Foo{
    public Foo(IService publicService){ ...... }
}

And

class Bar{
    public Bar(IService secretService){ ...... }
}

Then how can i achieve the following

Foo and Bar should get instances of publicService and secretService respectively, entirely based on name of their constructor parameters.

Gurpreet
  • 1,382
  • 11
  • 24
  • So what's your question? Is it not working? What are you seeing instead? What have you tried to get it to work? – Patrick Quirk Jan 31 '18 at 14:14
  • Sorry for the confusion, my Question was "how to implement the requirement". by i have now worked it out. Thanks – Gurpreet Jan 31 '18 at 14:58
  • Have a look at [Dependency Injection Unity - Conditional Resolving](https://stackoverflow.com/a/32415954/). Note that this answer will work with any DI container, not just Unity. There are additional examples of the strategy pattern [here](https://stackoverflow.com/a/34331154/) and [here](https://stackoverflow.com/a/31971691/). – NightOwl888 Feb 03 '18 at 19:32

1 Answers1

2

I have now made it to work using a custom SubDependencyResolver, i added this to the container and now it injects the implementation by name

public class ByParameterNameResolver : ISubDependencyResolver
{
    private readonly IKernel kernel;

    public ByParameterNameResolver(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public virtual bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
    {
        if (dependency.TargetItemType == null)
            return false;

        if (string.IsNullOrWhiteSpace(dependency.DependencyKey))
            return false;

        return kernel.HasComponent(dependency.DependencyKey);
    }

    public virtual object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
    {
        return kernel.Resolve(dependency.DependencyKey, dependency.TargetItemType);
    }
}
Gurpreet
  • 1,382
  • 11
  • 24
  • There might be some ifs and buts that i havn't explored yet. i guess we will find out soon unless you guys can spot something obvious. – Gurpreet Jan 31 '18 at 15:00