views:

435

answers:

3

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

A: 

How about...

var sp = container.Resolve(
  Type.GetType("ISearchable`1[" + yourGenericTypeHere + "]"));
Dmitri Nesteruk
Thanks for that Dmitri, though I'm hoping for a strongly typed solution - if there is one out there! :)
Andy Clarke
A: 

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.

Ade Miller
But I'd still need to get T dynamically into the resolve method ...
Andy Clarke
+3  A: 

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);
Andy Clarke