Enabling dependencies for extension classes?

I am using Microsoft Unity as an IoC container. I have several extension classes that add useful methods to my business objects. This is the code I use today:

public static class BusinessObjectExtensions { public static bool CanDoStuff(this BusinessObject obj) { var repository = BusinessHost.Resolver.Resolve<IRepository>(); var args = new EArgument { Name = obj.Name }; return repository.AMethod(obj.UserName, args); } } 

Is there a better way to manage dependency injection for extension classes?

+5
source share
3 answers

In fact, you should try to avoid extension methods if they do not work only with internal data (properties of the class itself) or simple data types provided in the method. You should not talk to other dependencies in your extension methods. If you follow this rule, you do not need to introduce extension classes using IoC.

+2
source

The actual default method for dependency injection by constructor injection is not possible for static classes. One could use the Injection parameter as shown below, however this is not a very clean way.

 public static class BusinessObjectExtensions { public static bool CanDoStuff(this BusinessObject obj, IRepository repository) { var args = new EArgument { Name = obj.Name }; return repository.AMethod(obj.UserName, args); } } 
+4
source

Why would you do this?

This increases the grip in the application with the roof and can confuse your teammates to use the extension method (they need to keep in mind that each time this method is used, they enter the repository each time).

Instead, create a separate class and use the constructor injection to inject an instance of IRepository :

 public class StuffExecuter { private readonly IRepository _repository; public StuffExecuter(IRepository repository) { _repository = repository; } public bool CanExecute(BusinessObject obj) { _repository.Add(obj.UserName, new EArgument { Name = obj.Name }); } } 
+1
source

Source: https://habr.com/ru/post/1244650/


All Articles