c#-以非通用方式绑定Ninject Factory Extension之后的异常
作者:互联网
我有以下代码:
public interface ILogging
{ ... }
public interface ILoggingFactory
{
ILogging CreateLogging();
}
public class MailSender : IMailSender
{
[Inject]
public MailSender(ILoggingFactory loggingFactory)
{
...
}
}
当我尝试将工厂绑定为
Bind<ILoggingFactory>().ToFactory();
一切都很好.否则,当我以非通用方式尝试时
Bind(myType).ToFactory();
我收到一个InvalidCastException
Unable to cast object of type ‘Castle.Proxies.ObjectProxy’ to type
‘MyLibrary.ILoggingFactory’
尝试加载使用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 });
评论:由于项目原因,我想以非通用方式绑定工厂.
解决方法:
如果您使用
Bind(myType).ToFactory();
Ninject为工厂类型Object而不是ILoggingFactory创建代理对象.您还必须指定工厂类型:
this.kernel.Bind(typeof(ILoggingFactory)).ToFactory(typeof(ILoggingFactory));
标签:dependency-injection,ninject,ninject-extensions,c 来源: https://codeday.me/bug/20191029/1960775.html