开发者

Anticipating possible circular-reference situation in upcoming .Net project idea... anything to watch out for?

So I've got this data access layer, and I also want to log to the database. In the spirit of eating my own dog food, I want to use my data access layer to do the logging. However, I also wa开发者_如何学Cnt to log the data access itself. Like so:

App
||
V
Log
||
V
Data=>Log

Am I at risk of getting into a feedback loop? If so, how should I avoid it? Could the references for the project loop onto each other and cause difficulty building? How have you successfully approached this (anti?) pattern in the past?


Create an assembly (or assemblies as the case may be) that only contain interfaces. Reference the interface only assembly from your concrete class assemblies and have every concrete class implement one or more interfaces. Do not have concrete class assemblies refer to other concrete class assemblies that are part of your solution.

This approach should help you avoid circular dependencies.

Implement a dependency injection/inversion of control container like StructureMap or one of the many other .NET options available to you to reduce coupling even further.


a possibly over-simplified solution:

public interface ILoggable {
    string ToLogFormat();
}

Then implement this interface on any object that can be logged. The logging layer now depends only on the interface, and can be used at any level.

an alternative is to use 'helper' classes to implement ToLogFormat via overloading, e.g.

public class LogHelper {
    public string ToLogFormat(DAO obj) { ... }
    public string ToLogFormat(SomeOtherClass obj) { ... }
    ...
}

you could use one monolithic log helper (which is bad, because it would have to reference every library) but a better solution might be to implement log helpers for each assembly or class and specify the name of the log-helper class using a custom attribute

personally, i prefer the ILoggable approach as being more flexible; your logging package could have a simple function in it like:

public class Logger {
    public string ToLogFormat(object obj) {
        if (obj is ILoggable) {
            return ((ILoggable)obj).ToLogFormat();
        }
        return obj.ToString();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜