Is there any way to use contructor injection using Autofac in a Xamarin.Android project? -
i'm throwing on xamarin.android version of existing app built heavily on microsoft stack (w8/wp8/silverlight etc..) , autofac used extensively throughout.
autofac prefers showing dependencies through constructor parameters, of course assumes i, coder, have control of creation of viewmodels/controllers, or in android's case... activities.
my question is: there way can use autofac in desired way considering android framework responsible activity creation? there can intercept activity creation resolve dependencies way autofac designed?
a possible workaround subclass activity, , mark dependencies custom attribute on writable properties.
then can use reflection yank properties out , inject them using autofac. not follow autofac's convention of marking dependencies in constructors, gets job done , injects properties mef does.
public class autofacactivity : activity { private static containerbuilder containerbuilder { get; set; } protected override void oncreate(bundle bundle) { base.oncreate (bundle); // bootstrap if (core.ioc.container == null) { new bootstrapper ().bootstrap (); } propertyinfo[] properties = this.gettype().getproperties(bindingflags.public | bindingflags.instance); foreach (var property in properties.where(p=>p.getcustomattributes(typeof(injectattribute), false).any())) { object instance = null; if (!core.ioc.container.tryresolve (property.propertytype, out instance)) { throw new invalidoperationexception ("could not resolve type " + property.propertytype.tostring ()); } property.setvalue (this, instance); } } }
this method works, feels little dirty. improvements make?
Comments
Post a Comment