Ninject工厂的自定义实例提供程序

时间:2014-06-23 15:08:14

标签: c# logging dependency-injection inversion-of-control ninject

我有以下两个界面:

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?

}

1 个答案:

答案 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))