Search code examples
c#dependency-injectionninjectninject-extensions

Exception after Binding Ninject Factory Extension in non generic way


I have following code:

public interface ILogging
{ ... }

public interface ILoggingFactory
{
  ILogging CreateLogging();
}

public class MailSender : IMailSender
{
  [Inject]
  public MailSender(ILoggingFactory loggingFactory)
  {
    ...
  }
}

When I try to bind my factory as

Bind<ILoggingFactory>().ToFactory();

everything is working fine. Otherwise, when I try it in non generic way

Bind(myType).ToFactory();

I get an InvalidCastException

Unable to cast object of type 'Castle.Proxies.ObjectProxy' to type 'MyLibrary.ILoggingFactory'

when trying to load an mail sender that uses the logginFactory as:

kernel.Get<IMailSender>();

Update:

The workaround I am using with reflection:

MethodInfo bindMethodInfo = GetType().GetMethods()
  .First(one => one.Name == "Bind" &&
  one.IsGenericMethod).MakeGenericMethod(mType);
var bindMethodResult = bindMethodInfo.Invoke(this, null);

MethodInfo toFactoryMethodInfo = typeof(Ninject.Extensions.Factory.BindToExtensions).GetMethods()
  .First(one => one.Name == "ToFactory" && one.IsPublic && one.IsGenericMethod &&   
  one.GetParameters().Count() == 1)
  .MakeGenericMethod(mType);

toFactoryMethodInfo.Invoke(bindMethodResult, new[] { bindMethodResult });      

Comment: For project reasons I want to bind the factory in non generic way.


Solution

  • If you use

    Bind(myType).ToFactory();
    

    Ninject creates a proxy object for factory type Object instead of ILoggingFactory. You have to additionally specify the factory type:

    this.kernel.Bind(typeof(ILoggingFactory)).ToFactory(typeof(ILoggingFactory));