Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity and Generics

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!

like image 697
William Avatar asked May 17 '11 05:05

William


People also ask

What are generic functions in unity?

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.

Does C# support generics?

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.

What is the generics in C#?

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.


2 Answers

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?

like image 127
Chris Tavares Avatar answered Oct 16 '22 15:10

Chris Tavares


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.

like image 28
Carles Company Avatar answered Oct 16 '22 17:10

Carles Company