A lot of people don’t seem to realize that setting readonly variables is indeed possible, it can only be done from inside the constructor:
public class SomeClass { private readonly ISomeService _someService; private readonly ISomeOtherService _someOtherService; public SomeClass(ISomeService someService, ISomeOtherService someOtherService) { _someService = someService; _someOtherService = someOtherService; } }
This is perfectly fine working code and I strongly recommend it. I use this a lot with dependency injection (DI). This makes sure that the injected instances cannot be overridden, because they can only be set in the constructor.
That’s why I really don’t like the requirement of a parameterless constructor in UserControls in WebForms. There is no possibility for injection, only resolving is possible.
Leave a Reply