c# - Passing Type to to method with generics -
hi tryng create generic wrapper around unity enable me change ioc frameworks whenever want without need of
public static void registertypes(idependencyinjectioncontainerwrapper container) { list<type> types = loadtypesfromassemblies(); foreach (var type in types) { var interfacetype= type.customattributes .firstordefault(a => a.attributetype.name == typeof(dependencyservice).name) .constructorarguments[0].value; container.registertype<type, interfacetype>(); } }
what's happening here getting list types attribute dependencyservice applyed.
then iterate on , getting first constructor argument of attribute.
i attempting register type in container threw generics.this having problems.
i not know how pass 2 types have in registertype method generics.as stands getting errors because passing in generic variable not object type
is there anyway solve problem?
if dependency container has non-generic method, call that:
container.registertype(type, interfacetype);
if doesn't have non-generic method, , if can modify source, i'd strongly recommend providing one; makes kind of thing lot easier. typically, container generic method end calling non-generic one:
public void registertype(type impltype, type ifacetype) { ... } public void registertype<timpl, tiface>() timpl : tiface { this.registertype(typeof(timpl), typeof(tiface)); }
otherwise you'll have dynamically provide generic parameters through reflection:
var methodinfo = container.gettype().getmethod("registertype"); var actualmethod = methodinfo.makegenericmethod(type, interfacetype); methodinfo.invoke(container);
but neither efficient nor particular elegant.
Comments
Post a Comment