Non Generic Binding - mariaheine/Zenject-But-Wiki GitHub Wiki
In some cases you may not know the exact type you want to bind at compile time. In these cases you can use the overload of the Bind
method which takes a System.Type
value instead of a generic parameter.
// These two lines will result in the same behaviour
Container.Bind(typeof(Foo));
Container.Bind<Foo>();
Note also that when using non generic bindings, you can pass multiple arguments:
Container.Bind(typeof(Foo), typeof(Bar), typeof(Qux)).AsSingle();
// The above line is equivalent to these three:
Container.Bind<Foo>().AsSingle();
Container.Bind<Bar>().AsSingle();
Container.Bind<Qux>().AsSingle();
The same goes for the To method:
Container.Bind<IFoo>().To(typeof(Foo), typeof(Bar)).AsSingle();
// The above line is equivalent to these two:
Container.Bind<IFoo>().To<Foo>().AsSingle();
Container.Bind<IFoo>().To<Bar>().AsSingle();
You can also do both:
Container.Bind(typeof(IFoo), typeof(IBar)).To(typeof(Foo1), typeof(Foo2)).AsSingle();
// The above line is equivalent to these:
Container.Bind<IFoo>().To<Foo>().AsSingle();
Container.Bind<IFoo>().To<Bar>().AsSingle();
Container.Bind<IBar>().To<Foo>().AsSingle();
Container.Bind<IBar>().To<Bar>().AsSingle();
This can be especially useful when you have a class that implements multiple interfaces:
Container.Bind(typeof(ITickable), typeof(IInitializable), typeof(IDisposable)).To<Foo>().AsSingle();
Though in this particular example there is already a built-in shortcut method for this:
Container.BindInterfacesTo<Foo>().AsSingle();