1

I'm trying to set up Registrations in Unity, and I'm having trouble getting exactly what I need.

Imagine I have the following definitions:

public interface ISomeInterface { ... }

public interface ISomeDependency { ... }

public class DependencyA : ISomeDependency { ... }

public class DependencyB : ISomeDependency { ... }

public class SomeClassA : ISomeInterface
{
    public SomeClassA(ISomeDependency dep){ ... }
}

public class SomeClassB : ISomeInterface
{
    public SomeClassB(ISomeDependency dep){ ... }
}

I then register them with Unity as follows:

Container.RegisterType<ISomeDependency, DependencyA>("DependencyA");
Container.RegisterType<ISomeDependency, DependencyB>("DependencyB");
Container.RegisterType<ISomeInterface, SomeClassA>("ClassA");
Container.RegisterType<ISomeInterface, SomeClassB>("ClassB");

I also register a factory that will build an ISomeInterface based off a key.

Container.RegisterType<Func<string, ISomeInterface>(new InjectionFactory(c=>
{
    return new Func<string, ISomeInterface>(x=>
    {
        return c.Resolve<ISomeInterface>(x)
    }
}));

(incidentally, if anyone knows a better way of creating keyed factories I'd welcome the tip)

How can I configure Unity such that when Unity builds me an instance of SomeClassA, it will also inject an instance of DependencyA? The same when Unity builds me an instance of SomeClassB, it will inject an instance of DependencyB.

Appreciate your help.

edit: corrected my typo

2
  • Once you start having multiple implementations of the same interface in the same object graph, Pure DI becomes a better option. Take a look at this article for more details: criticalsoftwareblog.com/index.php/2015/08/23/… Commented Feb 7, 2017 at 23:17
  • The use of factory abstractions (even if you use Func<T, R>) are typically a design smell. Commented Feb 8, 2017 at 8:16

1 Answer 1

1

If you register two concrete types for one interface, Unity will not know which one to resolve to. You'll have to provide more information. One way to do that is to use a parameter override.

// Override the constructor parameter "dep" value
// Use DependencyA instead of other value
var result = container.Resolve<ISomeInterface>(
    new ParameterOverride("dep", new DependencyA())
        .OnType<SomeClassA>());

But, you've also registered bot SomeClassA and SomeClassB as type of ISomeInteface, so you'll also have to tell Unity which one of those implementations you want when you want an ISomeInterface.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.