存储提供程序类中的依赖项注入,由记录器使用

时间:2015-02-19 11:43:27

标签: c# logging dependency-injection ninject

我正在编写自定义记录器并注入日志存储。我需要将请求记录到此存储。问题是这将是记录器和存储器之间的循环引用。在这种情况下,有没有办法提供松耦合?

像这样的Smth:

public interface ILogger{
    void Log(String msg);
}

public interface IStorage{
    void Save(String msg);
}

public class MyLogger:ILogger{

    private IStorage _storage;

    public MyLogger(IStorage storage){
        _storage = storage;
    }

    public void Log(String msg){
        _storage.Save(msg);
    }
}

public class MyStorage:IStorage{

    private ILogger _log;

    public MyStorage(ILogger logger){
        _log = logger
    }

    public void Save(String msg){
        _log.Log(msg);
        //....
        //send msg to a database like SQL, MongoDB, Cassandra or anything
    }

}

public class MyNinjectModule : NinjectModule
{
    public override void Load() 
    {
        Kernel.Bind<ILogger>().To<MyLogger>();
        Kernel.Bind<IStorage>().To<MyStorage>();
    }
}

0 个答案:

没有答案