c# - Ninject factory create T based on enum -
i want let ninject resolve instance of t based on specific enum input value.
i have read ninject's factory extension, couldn't find example having factory resolve specific class based on enum.
each class derives base class , derived class has several, different interfaces ninject has resolve.
for example how interface should like:
public interface iprocessfactory { t create<t>(processindex processindex) t : baseprocess; }
how can achieved ?
this not supported out of box. can customize writing own implementation of iinstanceprovider(also see ninject wiki entry. configure specific factory:
kernel.bind<ifoofactory>() .tofactory(() => new mycustominstanceprovider());
or alternatively, if want change behavior of .tofactory()
bindings: rebind iinstanceprovider
after loading ninject.extensions.factory
:
kernel.rebind<iinstanceprovider>().to<mycustominstanceprovider>();
however, if it's not need consider manually writing factory implementation @ composition root.
anyway, in both cases you'll need know how create conditional binding. ninject calls contextual binding. 1 method use binding-metadata:
const string enumkey = "enumkey"; bind<ifoo>().to<afoo>() .withmetadata(enumkey, myenum.a); iresolutionroot.get<ifoo>(x => x.get<myenum>(enumkey) == myenum.a);
another way create custom iparameter , use in conditional binding:
bind<ifoo>().to<afoo>() .when(x => x.parameters.oftype<myparameter>().single().value == a);
Comments
Post a Comment