i have problem resolving dependency in autofac. may related co/contra variance on type.
the following program returns 0, 1. means 2 call resolve not returns same types (whhereas same object serves type) expect return: 1,1. (the difference static type of var different, there way use runtime type ?)
thanks
icontainer _container; void main() { var builder = new containerbuilder(); builder.registertype<ahandler>().as<ihandler<a>>(); _container = builder.build(); ibase = new a(); console.writeline(resolve(a)); b = new a(); console.writeline(resolve(b)); } int resolve<t>(t a) t:ibase { return _container.resolve<ienumerable<ihandler<t>>>().count(); } // define other methods , classes here interface ibase{} interface ihandler<t> t:ibase {} class : ibase{} class ahandler : ihandler<a>{}
you'll need sort of runtime resolution of type. e.g. using dynamic keyword:
ibase = new a(); console.writeline(resolve((dynamic)a)); b = new a(); console.writeline(resolve((dynamic)b)); or using reflection:
int resolvedynamic(ibase a) { methodinfo method = typeof(icontainer).getmethod("resolve"); var handlertype = typeof(ihandler<>).makegenerictype(a.gettype()); var enumerabletype = typeof(ienumerable<>).makegenerictype(handlertype); methodinfo generic = method.makegenericmethod(enumerabletype); var result = (ienumerable<object>)generic.invoke(_container, null); return result.count(); }
Comments
Post a Comment