Registrating bindings

Bindings are registered with IInjectorBinder.
Bindings can be created using lambda expressions, by reflection, by method delegate, or by providing a ready-made instance.
Bindings are created using the Bind method of IInjectorBinder:
public interface IInterface { }
public class Alfa { }
public class Beta : Alfa, IInterface { }
public class Bravo : Beta { }

var injector = new MugenInjector();
injector.Bind<IInterface>().To<Beta>();
injector.Bind<Alfa, Beta>().To<Bravo>();
All registered services are checked and if you are write this code:
injector.Bind(typeof (Bravo)).To(typeof (Alfa));
you are get an error InvalidBindingException:
The service MugenInjectionDocumentation.Bravo not assignable from MugenInjectionDocumentation.Alfa.

Using Reflection

As you can see bindings can creating using Reflection.
Also supported open generic types:
injector.Bind(typeof (IRepository<>)).To(typeof (Repository<>));
injector.Get<IRepository<Alfa>>();
container supported self bindable types, if you are write this code, it will be correct:
var injector = new MugenInjector();
injector.Get<Alfa>();

Using method delegate

MugenInjector can accept a delegate to be used as a service creator:
var injector = new MugenInjector();
injector.Bind<B>().ToMethod(context => new B(context.CallInjector.Get<A>()));
For generic binding the delegate is as follows:
public delegate T MethodBindingDelegate<out T>(IBindingContext bindingContext);
For non-generic binding the delegate is as follows:
public delegate object MethodBindingDelegate(IBindingContext bindingContext);
It takes IBindingContext and returns an instance of service, more about IBindingContext see this.

Using Constant

MugenInjector can accept a ready-made instance as a service creator:
injector.Bind<Alfa>().ToConstant(new Alfa());

Using Expressions (only expression supported platforms)

MugenInjector can accept a lambda expression to be used for creating binding:
var injector = new MugenInjector();
injector.Bind<B>().To(context => new B(context.Resolve<A>()) {C = new C()});
This code is equivalent to:
injector.Bind<B>().ToSelf().TakeConstructor<A>().WithPropertyValue<C>("C", new C());
The expression not used for create service, it's used only for create binding.

Almost all methods described above have different overload.

Last edited Aug 12, 2012 at 11:38 AM by VVS0205, version 4

Comments

No comments yet.