6

我在这里链接我的类构造函数的动机是,我有一个默认构造函数供我的应用程序主流使用,还有一个允许我注入模拟和存根。

在 ":this(...)" 调用和从默认构造函数调用参数化构造函数中的“新”事物看起来有点丑陋,我想知道其他人会在这里做什么?

(仅供参考-> SystemWrapper

using SystemWrapper;

public class MyDirectoryWorker{

    //  SystemWrapper interface allows for stub of sealed .Net class.
    private IDirectoryInfoWrap dirInf;

    private FileSystemWatcher watcher;

    public MyDirectoryWorker()
        : this(
        new DirectoryInfoWrap(new DirectoryInfo(MyDirPath)),
        new FileSystemWatcher()) { }


    public MyDirectoryWorker(IDirectoryInfoWrap dirInf, FileSystemWatcher watcher)
    {
        this.dirInf = dirInf;
        if(!dirInf.Exists){
            dirInf.Create();
        }

        this.watcher = watcher;

        watcher.Path = dirInf.FullName;

        watcher.NotifyFilter = NotifyFilters.FileName;
        watcher.Created += new FileSystemEventHandler(watcher_Created);
        watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
        watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
        watcher.EnableRaisingEvents = true;
    }

    public static string MyDirPath{get{return Settings.Default.MyDefaultDirPath;}}

    // etc...
}
4

2 回答 2

3

包含默认构造函数是一种代码味道,因为现在该类与 IDirectoryInfoWrap 的具体实现耦合。为了让您的生活更轻松,请使用类外部的 IOC 容器来注入不同的依赖项,具体取决于您是运行测试代码还是主流应用程序。

于 2010-03-24T00:21:00.237 回答
0

我就是这样做的。

class MyUnitTestableClass
{
    public MyUnitTestableClass(IMockable foo)
    {
        // do stuff
    }

    public MyUnitTestableClass()
        : this(new DefaultImplementation())
    {
    }
}
于 2010-03-23T23:55:13.513 回答