-
I didn't put this in "language ideas" because I don't have a specific proposal, but if others agree it's a worthwhile use case to consider, that could lead to coming up with something worth proposing. I've recently started working in a codebase that uses a lot of dependency injection, and one thing I've noticed is that it prevents using extension methods in the way that I'm used to, because the dependencies can't be injected into the static extension method. A quick google search suggests I'm far from the first to encounter this. A simple example: public static class EmploymentExtensions
{
public static Employer GetEmployer(this Person person) => throw new NotImplementedException();
public static IEnumerable<Person> GetEmployees(this Employer employer) => throw new NotImplementedException();
} If these methods require database access, and the database access is available through an injected service or EF context rather than from something The best idea I've had so far - and it's not great - would be to allow declaring non-static extension methods, and some way to do an instance-level equivalent of public class MyService
{
using private readonly EmploymentExtensions employmentExtensions; // 'using' modifier registers the object as providing extension methods
public MyService(EmploymentExtensions employmentExtensions, ...)
{
this.employmentExtensions = employmentExtensions;
...
}
void doSomething(Employer employer)
{
// employer.GetEmployees() is equivalent to employmentExtensions.GetEmployees(employer)
foreach (var person in employer.GetEmployees()) ...;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 7 replies
-
My immediate thought is that extension methods should not be used here. I know it may seem "nice" to sprinkle all these helpful extension methods on |
Beta Was this translation helpful? Give feedback.
-
This feels like it fits under "roles": #5498 |
Beta Was this translation helpful? Give feedback.
-
Or possibly as "implicit parameters", if the goal is to be able to pass the |
Beta Was this translation helpful? Give feedback.
Or possibly as "implicit parameters", if the goal is to be able to pass the
Database
instance as an argument to these extension methods: #5989