Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity Container - Passing in T dynamically to the Resolve method

I've created an ISearchable interface that I've Typed so that I can retrieve an IEnumerable of T for the results.

I have a number of services that implement ISearchable for different domain objects ...

Container.RegisterType<ISearchable<Animal>, AnimalService>();
Container.RegisterType<ISearchable<Fish>, FishService>();

I want to resolve (through Unity) an ISearchable based on the type, but am struggling to get it to work ...

The following dosn't compile but will hopefully give an idea of what I'm trying to achieve.

Type t = typeof(Animal);
var searchProvider = _container.Resolve<ISearchable<t>>();

Any helped gratefully received!

Thanks,

Andy

like image 515
Andy Clarke Avatar asked Jul 13 '09 16:07

Andy Clarke


2 Answers

Finally sorted it, hopefully it'll be of help to someone else!

var type = filter.GetType();
var genericType = typeof(ISearchable<>).MakeGenericType(type);
var searchProvider = _unityContainer.Resolve(genericType);
like image 121
Andy Clarke Avatar answered Oct 31 '22 05:10

Andy Clarke


Why not register your types by name and resolve that way?

Container.RegisterType<ITelescopeView, TelescopeView>("type1");
Container.RegisterType<ITelescopeView, TelescopeView2>("type2");

Container.Resolve(ITelescopeView, "type1");

If you want your names can simply be the type's full name or you could use something else. Dmitri's approach will work too. But this might result in clearer code.

like image 31
Ade Miller Avatar answered Oct 31 '22 04:10

Ade Miller