Reputation: 53
I am using IUnityContainer
for Registering the types for resolving later.
I have registered the types as below:
// Register a "named type" mapping
container.RegisterType<IProcessHelper, FirstResponseHelper>("FirstResponseHelper");
container.RegisterType<IProcessHelper, SecondResponseHelper>("SecondResponseHelper");
Hence, I could able to use as below in one of my constructor:
public Finish(
IUnitOfWork unitOfWork ,
ILog logger,
..........
[Dependency("FirstResponseHelper")] IProcessHelper firstResponseHelpe,
[Dependency("SecondResponseHelper")] IProcessHelper secondResponseHelper
)
{
.........
_firstResponseHelpe = firstResponseHelper;
_secondResponseHelper = secondResponseHelper;
}
...and would like to get it resolved using Substitute, something-like "below". But by passing the "name" => "FirstResponseHelper" is not allowed in Substitute! :(
// Trying to resolve in UnitTest, looks like below (passing name)
IProcessHelper firstResponseHelper = Substitute.For<IProcessHelper>("FirstResponseHelper")
IProcessHelper secondResponseHelper = Substitute.For<IProcessHelper>("SecondResponseHelper")
I need to call a method from FirstResponseHelper & SecondResponseHelper, from my UnitTest (MSTest).
Hence, I need to get it resolved using Substitute.For<>
for the "named type" interface.
Upvotes: 0
Views: 295
Reputation: 22655
I'm assuming that you want to register a Substitute as named registration so that you can resolve Finish
. If that is the case then you can use an InjectionFactory
to return the substitute:
container.RegisterType<IProcessHelper>("FirstResponseHelper",
new InjectionConstructor(c => Substitute.For<IProcessHelper>()));
container.RegisterType<IProcessHelper>("SecondResponseHelper",
new InjectionConstructor(c => Substitute.For<IProcessHelper>()));
As an aside I wouldn't use the [DependencyAttribute]
and instead remove those attributes and define an InjectionConstructor
that passes in the correct dependencies:
container.RegisterType<Finish>(
new InjectionConstructor(
new ResolvedParameter<IUnitOfWork>(),
new ResolvedParameter<ILog>(),
new ResolvedParameter<IProcessHelper>("FirstResponseHelper"),
new ResolvedParameter<IProcessHelper>("SecondResponseHelper")));
or an InjectionFactory
that does something similar:
container.RegisterType<Finish>(
new InjectionFactory(c =>
{
return new Finish(c.Resolve<IUnitOfWork>(),
c.Resolve<ILog>(),
c.Resolve<IProcessHelper>("FirstResponseHelper"),
c.Resolve<IProcessHelper>("SecondResponseHelper")
}));
Upvotes: 1