how do i register and resolve a generic object/interface in Unity? I'm trying to stay away from the config file.
I'm looking for something like
IEnterpriseClient<IInterface1>
to resolve to EnterpriseClient<IInterface1>
The class signature is
class EnterpriseClient<T> : IEnterpriseClient<T> where T : class
Thanks!
The Unity Scripting API Reference documentation lists some functions (for example, the various GetComponent functions) with a variant that has a letter T or a type name in angle brackets after the function name: //C# void FuncName<T>(); These are generic functions.
C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static methods, properties, events, delegates, and operators using the type parameter and without the specific data type.
Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.
It's pretty much exactly what you'd think:
container.RegisterType<IEnterpriseClient<IInterface1>, EnterpriseClient<IInterface1>>( ... );
That's if you only want that particular closed generic registered. For the open generic (not just IInterface1), you can do:
container.RegisterType(typeof(IEnterpriseClient<>), typeof(EnterpriseClient<>), ... );
You mentioned you'd tried this - what's not working?
Look at this question for XML configuration: Unity 2.0 registering generic types via XML
and http://davidhayden.com/blog/dave/archive/2008/03/25/UnityDependencyInjectionOpenGenericTypes.aspx for code configuration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With