Records are great for encapsulating data, but what about things like services and repositories? The positional syntax for property definition is more concise compared to class definition code, since the constructor, properties, and property initialization code are generated by the compiler for us.
Here is a contrived example to demonstrate. The intent is to make the dependencies of RecordService immutable in fewer lines of code. In a real-world scenario, the dependencies would be injected by a service container.
namespace RecordsTest;
class MyRepo
{
public string SomeMethod() => "MyRepo.SomeMethod()";
}
class MyService
{
public string SomeMethod() => "MyService.SomeMethod()";
}
record RecordService(MyRepo Repo, MyService Service)
{
public void SomeMethod() =>
Console.WriteLine($"RecordService.SomeMethod() {Repo.SomeMethod()} {Service.SomeMethod()}");
}
class Program
{
static void Main(string[] args)
{
var myRepo = new MyRepo();
var myService = new MyService();
var recordService = new RecordService(myRepo, myService);
recordService.SomeMethod();
Console.ReadKey();
}
}