c# - Creating objects based on a string using Ninject -
i need create objects sharing common interface (ifoo) based on string database. have "a", need intantiate afoo, "b", need produce bfoo, etc. first thing tought of factory. objects created (afoo, bfoo) need have dependencies injected (and dependencies need more dependencies , arguments). injecting use ninject, seems fancy factory. create objects within factory inject ninject's kernel via constructor. desired way?
interface ibar { } class bar : ibar { public bar(string logfilepath) { } } interface ifoo { } class afoo : ifoo { public afoo(ibar bar) { } } class bfoo : ifoo { } class foofactory : ifoofactory { private ikernel _ninjectkernel; public foofactory(ikernel ninjectkernel) { _ninjectkernel = ninjectkernel; } ifoo getfoobyname(string name) { switch (name) { case "a": _ninjectkernel.get<afoo>(); } throw new notsupportedexception("blabla"); } } class foomanager : ifoomanager { private ifoofactory _foofactory; public foomanager(ifoofactory foofactory) { _foofactory = foofactory; } void donastyfoothings(string text) { ifoo foo = _foofactory.getfoobyname(text); /* use foo... */ } } class program { public static void main() { ikernel kernel = new standardkernel(); kernel.bind<ibar>.to<bar>(); kernel.bind<ifoomanager>.to<foomanager>(); kernel.bind<ifoofactory>.to<foofactory>(); ifoomanager manager = kernel.get<ifoomanager>(new constructorargument("ninjectkernel", kernel, true)); manager.donastyfoothings("a"); } }
ninject's ikernel
's get<t>()
method has overload takes name argument named instance.
the usage be:
public int main() { ikernel kernel = new standardkernel(); kernel.bind<ifoo>().to<afoo>().named("afoo"); kernel.bind<ifoo>().to<bfoo>().named("bfoo"); //returns afoo instance var afoo = kernel.get<ifoo>("afoo"); //returns bfoo instance var bfoo = kernel.get<ifoo>("bfoo"); }
regarding question injecting ninject's ikernel
factory
's constructor, don't think there should problems. factory should this:
public interface ifoofactory { ifoo getfoobyname(string name); } public class foofactory : ifoofactory { private readonly ikernel _kernel; public foofactory(ikernel kernel) { _kernel = kernel; } public ifoo getfoobyname(string name) { return _kernel.get<ifoo>(name); } }
also add binding ikernel
this:
kernel.bind<ikernel>().toconstant(kernel);
Comments
Post a Comment