Injecting into private field of a base class doesn't work
See original GitHub issueIf I have a private field with the Inject
attribute in a base class, it won’t be injected upon resolving.
public class DataManager { }
public class BaseData
{
[Inject] private DataManager _dataManager;
}
public class LevelData : BaseData { }
...
var builder = new ContainerBuilder();
builder.Register<DataManager>(Lifetime.Scoped).AsSelf();
builder.Register<LevelData>(Lifetime.Scoped).AsSelf();
var container = builder.Build();
var levelData = container.Resolve<LevelData>();
At this point, levelData._dataManager
is null. But if I change private to protected, the field will be injected.
Is this the desired behavior?
Issue Analytics
- State:
- Created a year ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
How to inject a private field in a Component class while ...
First lets take a look at your plans and bust some myths/misunderstandings. Plan A: Using constructor to initiate the private field.
Read more >Avoid private field dependency injection - here is why
Dependency injection is a great way of decoupling system components, assuming they are written using a contract-implementation approach.
Read more >When extending a class, use an injected object of that class
The problem in your second snippet is that the child should not extend but implement the parent interface. You may then very well...
Read more >ASP.NET Core Blazor dependency injection
This article explains how Blazor apps can inject services into components. Dependency injection (DI) is a technique for accessing services ...
Read more >Java static code analysis: Private fields only used as local ...
When the value of a private field is always assigned to in a class' methods before being read, then it is not being...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
The behavior is due to the C# language specification.
VContainer’s field injection is done in the generated extension methods, but C# extension methods cannot access private variables in the type they are extending.
Constructor Injection or Method Injection can be used for Injection to private variables.
Fixed in #468 #505