Reputation: 5799
I'm trying to determine how I could inject a specific instance of a service when resolving a type.
For example with Unity I might do something like:
IFoo fooService = Container.Resolve<IFoo>();
fooSerivce.DoBar( "someParameter" );
ParameterOverrides overrides = new ParameterOverrides()
{
{ "fooService", fooService }
};
return Container.Resolve( type, overrides );
How would I accomplish this with Simple Injector?
Upvotes: 0
Views: 479
Reputation: 172646
Simple Injector has no built-in support for supplying the container's 'resolve' method, because this a bad idea in general since its main use case is to supply injection constructors with runtime data. Having the construction of your application components depend on runtime data is an anti-pattern, as expressed in detail here.
There are some rare cases though where you can't work around this, which mainly happens when integrating with 3rd party linraries or frameworks that are out of your control to change. You might be hitting such case with Prism, which seems to be designed around having a cyclic dependency between the page and the navigation service, which is the main reason why prism is doing this.
You should take a look at this particular Q&A. It talks about WebFromsMvp which has the same design quirk as Prism does. The question and answer describe a way to work around this quite effectively with Simple Injector.
UPDATE
From the example you show in your question, there doesn't seem a need to use overrides at all, since you inject a service that has been resolved from the container. Instead you can do the following:
IFoo fooService = Container.GetInstance<IFoo>();
fooSerivce.DoBar("someParameter");
return Container.GetInstance(type);
As long as IFoo
is registered with a Scoped
or Singleton
lifestyle, and type
accepts an IFoo
in its constructor, the same instance is injected the revoled type
.
Upvotes: 1