Mugen Injection [Adapters]
The adapter pattern takes one service contract and adapts it (like a wrapper) to another.
The MugenInjection provides built-in adapter registration so you can register a set of services and have them each automatically adapted to a different interface.
Adapter without condition
This code shows how to register the adapter for all types from IAlpha to IBeta, and then unregister it:public interface IAlpha { } public interface IBeta { IAlpha Alpha { get; } } public class Alpha : IAlpha { } public class Beta : IBeta { public Beta(IAlpha alpha) { Alpha = alpha; } public IAlpha Alpha { get; private set; } } // Create your MugenInjector. _injector = new MugenInjector(); var value = new Alpha(); _injector.Bind<IAlpha>().ToConstant(value); //Registering the adapter from IAlpha to IBeta _injector.BindAsAdapterForAll<IAlpha, IBeta>((context, alpha) => new Beta(alpha)); var beta = _injector.Get<IBeta>(); //beta.Alpha - Alpha equals to value //Unregistering the adapter from IAlpha to IBeta _injector.UnbindAllAdaptersFor<IAlpha, IBeta>(); //We get exception beta = _injector.Get<IBeta>();
Adapter with condition
This code shows how to register the adapter only for types with specific condition, and then unregister it:// Create your MugenInjector. _injector = new MugenInjector(); const string named = "named"; Type typeInto = typeof (Program); var value1 = new Alpha(); var value2 = new Alpha(); _injector.Bind<IAlpha>().ToConstant(value1).NamedBinding(named); _injector.Bind<IAlpha>().ToConstant(value2).WhenInto(typeInto); //Registering the adapter from IAlpha to IBeta _injector.BindAsAdapterFor<IAlpha, IBeta>(builder => builder.Named(named), (context, alpha) => new Beta(alpha)); _injector.BindAsAdapterFor<IAlpha, IBeta>(builder => builder.WhenInto(typeInto), (context, alpha) => new Beta(alpha)); //We get exception, because we don't have binding without condition //var beta = _injector.Get<IBeta>(); var beta = _injector.Get<IBeta>(named); //beta.Alpha - Alpha equals to value1 beta = _injector.GetInto<IBeta>(typeInto); //beta.Alpha - Alpha equals to value2 //Unregistering the adapter from IAlpha to IBeta var dict = new Dictionary<string, object>(); SpecialParameterKeys.SetKeyedBindingParameter(dict, named); _injector.UnbindAdaptersFor<IAlpha, IBeta>(null, null, dict, null); _injector.UnbindAdaptersFor<IAlpha, IBeta>(typeInto, null, null, null); //We get exception beta = _injector.Get<IBeta>(named); beta = _injector.GetInto<IBeta>(typeInto);