I am trying to bind a Func to an implementation of IService (Service1). Service1 takes the supplied IFormatter as a parameter. The type that is requesting the Service1 will be supplying the formatter instance (which is why im using a Func instead of just plain old IService. This is what I have done so far:
Bind<Func<IFormatter, IService>>()
.ToMethod(context => formatter =>
context.Kernel.Get<Service1>(new Parameter("formatter", formatter, false)));
Bind<Service1>().ToSelf().InSingletonScope();
This throws: “Injection of dependency IFormatter into parameter formatter of constructor of type Service1”.
how can i achieve a singleton of Service1 and allow the calling type to supply the IFormatter dependancy? i could get this working by simply:
Bind<Func<IFormatter, IService>>()
.ToMethod(context => formatter => new Service1(formatter))
.InSingletonScope();
however the returned Service1 instance is not a singleton. is this possible?
You have to use
ConstructorArgumentinstead ofParameter.Furthermore, I’d rethink your design. I think something is wrong with it. If you call the Func twice with different formatter instances you will not get what you would expect the second time if the service is a singleton. Most likely it is better to use a conditional binding for IFormatter than passing it to the service using a constructor argument.