Reputation: 147
I have a situation, where the constructor of a class requires two instances of the same concrete type implementing an interface. This is to enable use of "Tasks" to run them in parallel to reduce time.
The constructor code is like this:
public SomeUsingClass (ISomeDependency someDepOne, ISomeDependency someDepTwo) { }
Here, I have just one concrete class that implements ISomeDependency, which is SomeDependencyClass.
When I get an instance of SomeUsingClass, I must ensure that the two arguments are pointing to separate instances of SomeDependencyClass. This is because, when the instances are going to be used under two separate Tasks, their "states" should not conflict with the other.
I tried using named instances of ISomeDependency (named them as "instanceOne", and "instanceTwo". The code looks like below:
.For<ISomeDependency>().Add<SomeDependency>().Named("instanceOne");
.For<ISomeDependency>().Add<SomeDependency>().Named("instanceTwo");
... and, then used the following to create an instance of the using class:
.For<SomeUsingClass>().Use<SomeUsingClass>()
.Ctor<ISomeDependency>("someDepOne")
.IsNamedInstance("instanceOne")
.Ctor<ISomeDependency>("someDepTwo")
.IsNamedInstance("instanceTwo");
This results in the following error:
No default Instance is registered and cannot be automatically determined for type 'ISomeDependency'.
I had explicitly mentioned to use a particular instance with name. Where did I go wrong?
Upvotes: 1
Views: 399
Reputation: 591
All you need is to specify that in registration with AlwaysUnique()
:
.For<ISomeDependency>().AlwaysUnique().Add<SomeDependency>().Named("instanceOne");
.For<ISomeDependency>().AlwaysUnique().Add<SomeDependency>().Named("instanceTwo");
Upvotes: 0