以非通用方式绑定Ninject Factory Extension之后的异常

时间:2014-05-19 12:32:54

标签: c# dependency-injection ninject ninject-extensions

我有以下代码:

public interface ILogging
{ ... }

public interface ILoggingFactory
{
  ILogging CreateLogging();
}

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

当我尝试将我的工厂绑定为

Bind<ILoggingFactory>().ToFactory();
一切都运转良好。否则,当我以非通用方式尝试时

Bind(myType).ToFactory();

我收到InvalidCastException

  

无法转换类型&#39; Castle.Proxies.ObjectProxy&#39;的对象输入   &#39; MyLibrary.ILoggingFactory&#39;

尝试加载使用logginFactory的邮件发件人时:

kernel.Get<IMailSender>();

更新

我使用反射的解决方法:

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 });      

评论:出于项目原因,我想以非通用的方式绑定工厂。

1 个答案:

答案 0 :(得分:4)

如果您使用

Bind(myType).ToFactory();

Ninject为工厂类型Object而不是ILoggingFactory创建代理对象。您还必须另外指定工厂类型:

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