About .NET, ASP.NET, MVC, C#, WPF, WCF and everything related to .NET and more.

Mugen Injection [Constructor selection]

When you register a service you can specify the constructor which will be used to create the service, this code shows how it work:

// 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();
If you want complete control constructor selection, you can implement the IConstructorResolver interface, it's look like this:
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
}
And then we can write this code to use the constructor-resolver:
// Create your MugenInjector.
_injector = new MugenInjector();
_injector.Bind<Alpha>().ToSelf().UseCustomConstructorResolver(new MyConstructorResolver());
You can also make it default for all bindings:
// Create your MugenInjector.
_injector = new MugenInjector();
_injector.Settings.DefaultConstructorResolverFactory = () => new MyConstructorResolver();

Comments
Leave a Reply
*bold*
_italics_
+underline+
* Bullet List
** Bullet List 2
# Number List
## Number List 2
{"Do not apply formatting"}
{code:language} code here {code:language}.
Supports: aspx c#, c#, c++, html, sql, xml
[url:http://www.example.com]