0

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.

Kryptonian
  • 860
  • 3
  • 10
  • 26
  • i think you'll have to have a look into reflection here. – Franz Gleichmann Oct 19 '20 at 17:14
  • Does this answer your question? [How do I use reflection to call a generic method?](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) – Franz Gleichmann Oct 19 '20 at 17:14
  • Of what use is an object that has no (known) interface? If you cast later, you could just use the target type of the cast for resolving, if you don't cast, you can do nothing with it. – Haukinger Oct 19 '20 at 18:18
  • 1
    Could you explain to us **why** you are doing this? It seems like you are trying to solve an problem in the wrong way, but you are not telling us what that problem is: http://xyproblem.info/ – Xerillio Oct 19 '20 at 18:38
  • The problem if i try to explain more is I want to create object management using unity and to keep this simple I want to use it with ID. 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. – Kryptonian Oct 22 '20 at 14:02

1 Answers1

0

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.

Haukinger
  • 10,420
  • 2
  • 15
  • 28