我有以下两个界面:
public interface ILogger {}
public interface ILoggerFactory {}
ILoggerFactory包含一个方法GetLogger
,它将调用类的Type
作为参数,并返回一个实现ILogger
的记录器实例。现在我想声明一个实例提供程序,它自动连接所有内容,以便我可以将我的记录器直接注入一个类。我尝试了以下方式:
Kernel.Bind<ILoggerFactory>().To<MyCustomLoggerFactory>();
Kernel.Bind<ILogger>().ToFactory(() => new LoggerFactoryInstanceProvider());
public class LoggerFactoryInstanceProvider : StandardInstanceProvider {
protected override ... // what goes here?
}
答案 0 :(得分:2)
怎么样:
Kernel.Bind<ILoggerFactory>().To<MyCustomLoggerFactory>();
IBindingRoot.Bind<ILogger>().ToProvider<LoggerProvider>();
public class LoggerProvider : Provider<ILogger> {
private readonly ILoggerFactory factory;
public LoggerProvider(ILoggerFactory factory)
{
this.factory = factory;
}
protected override T CreateInstance(IContext context)
{
return this.factory.GetLogger(context.Request.ParentRequest.Service);
}
}
如果你有:
public class Foo
{
public Foo(ILogger logger) { }
}
然后ninject将使用提供程序创建ILogger
实例。提供商将返回ILoggerFactory.GetLogger(typeof(Foo))
。