New to Vala. Is there a recommended IOC Container for use in desktop apps.
1 Like
Forgive me if I make some mistakes here, since it’s been almost a decade since I last had anything to with code that dealt with IOC containers.
As far as I know, GObject doesn’t really have a IOC container, but thanks to the GObject type system, it should be relatively straightforward to make something yourself. There are 2 concepts you will need here:
- a
GLib.Type
(in C:GType
) which you can instantiate (so no abstract class). This is also the return value of thetypeof()
function. - the generic way of making objects
GLib.Object.new()
(in C:g_object_new()
), which takes such as Type as its first parameter
For example, assume that you have 2 interfaces Foo
and Bar
, which have an implementing class: FooImpl
and BarImpl
. You can make a factory class like this: (warning: I haven’t tried running this)
public class ObjectFactory : Object {
// Save the types into a variable.
// Option 1. Provide the types of the impls here
private Type foo_type = typeof(FooImpl);
private Type bar_type = typeof(BarImpl);
// Option 2. You can make a constructor to pass on the types
// instead of creating them by default
// public ObjectFactory(Type foo_type, Type bar_type) {
// this.foo_type = foo_type;
// this.bar_type = bar_type;
// }
/**
* Creates an instance of {@link Foo}.
*/
public Foo createFooInstance() {
return (Foo) Object.new(this.foo_type);
}
/**
* Creates an instance of {@link Bar}.
*
* We assume that Bar has a construct property `name`,
* to show how to pass on extra parameters.
*/
public Bar createBarInstance(string name) {
return (Bar) Object.new(bar_type, "name", name);
}
}
2 Likes
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.