简体   繁体   中英

How to use a FileSystemWatcher in a layered architecture?

Perhaps I am looking into the wrong architecture all together. If we assume that we have the UI, application, domain and infrastructure layers, what would be a good way to represent a file system watcher? My application essentially wants to get new files from an input folder and move them to an output folder. This is of course simplified but I can't seem to find good resources on how to structure such a thing.

The use cases from the UI are to add and remove input->output pairs and add new ones. When a new one is added, I'd want a file system watcher to be listening in another thread and call its callbacks from another thread (such that it will not block). It's callbacks would be setup by the application layer use case handler, where a domain object's function would be plugged into the interface (maybe adapted as well if needed). I would use a factory to create the IFileSystemWatcher from the input string. When one is removed, I would want to stop all callback threads and the file system watcher thread. A threadpool for handling callbacks would probably be a good idea.

Im mostly unsure where the threads should be made and managed, what layer a file system watcher would belong and where the implementation details of the things described above belong. I can't seem to find much information about these kinds of event producing long running tasks that call callbacks, where the events aren't really domain events (as far as I can see)

I believe the interface would be in the domain as the domain's purpose is to detect files, but perhaps thats a naive view and it is an application level thing. Regardless, I would see the interface as something like

public interface IFileSystemWatcher {
    void StartWatching();
    void StopWatching();
    void RegisterCallback(Action<FileSystemEvent> callback);
}

I've been stuck on this for a really long time and don't really have anyone to ask. I've tried to make it generic enough such that it is useful for others as well while also helping me specifically.

TL;DR How to work with and manage event producing background threads.

In my view threading issues are infrastructure layer, that can take care of bootstrap the file watcher, and as soon as it is notified it can transform that event into a "domain" one. Why you do you think these events are not domain ones? Can they be part of a different subdomain?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM