Resolve without Type information in unity

145 views Asked by At

Unity supports resolve based on types

T obj = container.Resolve<T>("id");

that means without knowing T, I can not resolve, I am writing some extension methods for my unity container where I want to add Resolve method which would return object type.

object obj = container.Resolve("id");

because when registering I already know T so I can keep type in a dictionary with "ID". This is unreliable as unity can itself resolve some types(even when not registered) Is there a simpler and reliable way to do resolve using only the Id for resolving?

This is diffrent from calling generic method from reflection due to performance issues and also since the resource is already registered with unity for DI hence i want to use existing solution to keep it consistent.

1

There are 1 answers

0
Haukinger On

Now if i can resolve something by ID and return object or dynamic i can use type converters internally to convert it to expected type later. Upfront i do not know type which has to be used.

If object is your interface, you can use that, of course:

container.RegisterType<object, ObscureService>( "service" );
container.RegisterType<object, SecretPlugin>( "plugin" );

object unknown = container.Resolve<object>( "service" );
object anotherUnknown = container.Resolve<object>( "plugin" );

This has very limited (sensible) use, though. I'd say you should only use this if you act on direct request from the user and the resolved unknown is some kind of view model that's only used to be presented back to the user.

If code requests the object, there's no reason why that code should not somehow be able to know what it's requesting.