通过构造函数初始化实现冗余

时间:2013-12-24 06:35:32

标签: c# constructor initialization

我有两个使用记录器的课程。

public class FooClass
{
    private readonly ILogger _logger;
    private readonly IBarClass _barClass;

    public FooClass() : this (new Logger(), new BarClass())
    { }

    public FooClass(ILogger logger, IBarClass barClass)
    {
        _logger = logger;
        _barClass = barClass;
    }

    public void FooMethod()
    {
        //Do something
    }
}

public class BarClass : IBarClass
{
    private readonly ILogger _logger;

    public BarClass() : this (new Logger())
    { }

    private BarClass(ILogger logger)
    {
        _logger = logger;
    }

    public void BarMethod()
    {
        //Do something
    }
}

似乎记录器在FooClass和BarClass中初始化了两次。我不能使用在FooClass中初始化的记录器在BarClass中使用。是否有其他解决方案可以解决这个问题。

请注意,FooClass的实例必须通过空构造函数调用。 (这个例子是我面临的问题的确切简单版本)

1 个答案:

答案 0 :(得分:1)

interface ILogger { }
class Logger : ILogger { }

interface IBarClass { }
class BarClass : IBarClass
{
    private readonly ILogger _logger;

    public BarClass(ILogger logger)
    {
        _logger = logger;
    }

    public void BarMethod()
    {
        //Do something
    }
}

class FooClass
{
    private readonly ILogger _logger;
    private readonly IBarClass _barClass;

    public FooClass()
    {
        _logger = new Logger();
        _barClass = new BarClass(_logger);
    }

    public FooClass(ILogger logger, IBarClass barClass)
    {
        _logger = logger;
        _barClass = barClass;
    }

    public void FooMethod()
    {
        //Do something
    }
}

我错过了什么吗?