Reputation: 644
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
Upvotes: 1
Views: 750
Reputation: 35881
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
.
Upvotes: 1