Andy Clarke
Andy Clarke

Reputation: 3262

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

Upvotes: 7

Views: 4082

Answers (3)

Dmitri Nesteruk
Dmitri Nesteruk

Reputation: 23789

How about...

var sp = container.Resolve(
Type.GetType("ISearchable`1[" + yourGenericTypeHere + "]"));

Upvotes: 0

Andy Clarke
Andy Clarke

Reputation: 3262

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

Upvotes: 12

Ade Miller
Ade Miller

Reputation: 13723

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.

Upvotes: 2

Related Questions