Mugen Injection [Выбор конструктора]
Когда вы регистрируете компоненты, вы можете задать конструктор, который будет использоваться для создания компонента, этот код показывает, как это работает:
// Create your MugenInjector. _injector = new MugenInjector(); //Takes constructor with string argument _injector.Bind<Alpha>().ToSelf().TakeConstructor(context => new Alpha(context.Resolve<string>())); _injector.Bind<Alpha>().ToSelf().TakeConstructor(typeof(string)); //Take empty constructor _injector.Bind<Alpha>().ToSelf().TakeConstructor();
Пример кода:
public class MyConstructorResolver:IConstructorResolver { #region Implementation of IConstructorResolver /// <summary> /// Selects constructor for the specified service type. /// </summary> /// <param name="service">The specified service <see cref="Type"/>.</param> /// <param name="bindingContext">The specified <see cref="IBindingContext"/>s.</param> /// <returns> /// An instance of the <see cref="ConstructorInfo"/>. /// </returns> public ConstructorInfo Resolve(Type service, IBindingContext bindingContext) { //Always returns constructor with empty types. return service.GetConstructor(Type.EmptyTypes); } /// <summary> /// Sets the <see cref="T:System.Reflection.ConstructorInfo"/> to the current <see cref="IConstructorResolver"/>. /// </summary> /// <param name="constructorInfo">The specified <see cref="ConstructorInfo"/></param> public void SetConstructor(ConstructorInfo constructorInfo) { throw new NotSupportedException(); } #endregion }
// Create your MugenInjector. _injector = new MugenInjector(); _injector.Bind<Alpha>().ToSelf().UseCustomConstructorResolver(new MyConstructorResolver());
// Create your MugenInjector. _injector = new MugenInjector(); _injector.Settings.DefaultConstructorResolverFactory = () => new MyConstructorResolver();