The S of SOLID stands for SRP (Single Responsibility Principle). You won't violate it by using System.IO.File
inside a class directly, once you keep that class with one single responsibility.
It's a good idea trying to abstract the purpose behind using System.IO.File
. Let's suppose you need it to generate a log. Then you would probably do something like:
public interface IMyLogger
{
void GenerateLog(IEnumerable<string> content);
}
public class FileLogger: IMyLogger
{
public void GenerateLog(IEnumerable<string> content)
{
System.IO.File.WriteAllLines("C:/Log", content);
}
}
Maybe it's not just a log, it's something more important, like generating a file so other system/app (even external) read it and do some job.
If you are trying to use a DDD approach, the interface could belong to your domain, and the implementation could belong in the application. Then you register your interface as a service and inject it.
The class which needs an IMyLogger
actually doesn't need to know how is the log being generated, it just needs the job to be done.
You can apply the same idea when you need to send an email inside some business logic in your domain. Instead of making a connection to an Exchange inside your domain directly, create an interface INotifier
and a MailNotifier
implementing it to be injected.
System.IO.File
inside a method right? You don't inject methods, but classes so I don't see a problem here. What I mean is, wrap it inside a service and inject that. – BrenzaFile
object but nothing more), otherwise your code will become impossible to test. – FreemasonryDateTime.Now
method, you should see plenty of code snippets that show you how you would abstract that into an interface. (e.g. anIDateTimeNowProvider
) – FreemasonrySystem.IO.File
without violating the dependency inversion principle? Or maybe I haven't understood the injection of my own file manager interface. – Gustie