Dependency injection through method with Resharper or DevExpress
-
12-06-2021 - |
Domanda
I want to inject a dependency in one of my class and I don't know if there is a refactor in tools like Resharper
or DevExpress
to do that.
Here is my class:
public class ClassWithInjections
{
private Dependency _fieldInjected;
}
public class Dependency
{
}
And the final result I want it to look like: (Note that the field can now be initialized by the method Initialize
)
public class ClassWithInjections
{
private Dependency _fieldInjected;
public void Initialize(Dependency fieldInjected)
{
_fieldInjected = fieldInjected;
}
}
I want to be able to just activate a refactor option while specifying my field with the mouse cursor and then the tool that could suggest me if I want to inject the dependency with method, property or constructor.
With Resharper
, you can do that with 'Encapsulate field' (Ctrl+Shift+R) or creating a constructor with the code generation tool (Alt-Insert) but I don't found any option to inject my dependency with the 'method' technique.
Anybody have the solution?
Soluzione
You can use the DevExpress Refactor! Pro > Create Setter Method refactoring option for this purpose.
Altri suggerimenti
First of all. You should not inject dependencies using methods. Read here. I would only use property injection to solve the circular dependencies problem.
That leaves constructor injection.
Resharper can help you. Press ALT+ENTER
on the field and choose "Initialize in constructor"
I don't found any option to inject my dependency with the 'method' technique.
Well. It doesn't exist since you should avoid that ;)