I have few validations to be done for a domain entity which requires DB Call.So i wanted to use my repository object in my domain model.I tried using Dependency injection but it does not do the work,and gives me null
public class ObjectX : Base
{
public IObjectRepository _ObjectRepository;
public Location(IObjectRepository objRepo)
{
this._ObjectRepository= objRepo;
}
int someProperty{get; set;}
bool validateProperty()
{
bool isValid =_ObjectRepository.ValidateProperty(someProperty);
return isValid;
}
So here the objRepo is coming null and hence the constructor also assigns null to _ObjectRepository.I have put the <IObjectRepository ,ObjectRepository> in Startup.cs
Is it possible to access the repository object here in domain model ?
2
Answers
Have you added it to your IoC container? You can do it in your startup file,
With data-centric objects, such as Domain Entities, it is not a common approach to have dependencies injected in the object’s constructor. It’s not that it’s impossible to resolve those dependencies from a DI Container, but DI Containers are meant to build up object graphs of components, which tend to be long lived, not data objects, which tend to be short lived. Generally speaking, mixing runtime data and stored dependencies in the same (data) object can lead to many complications. It comes down to Nikola’s 1st law of IoC:
Instead, a more common approach is to move from Constructor Injection (as you are doing in your example) to Method Injection. With Method Injection you can supply an already initialized object with a dependency through its public API, without the need for that object to store its incoming dependency.
In your case, the use of Method Injection would result in the following code:
Notice how:
ObjectX
‘s public API (validateProperty
) accepts theIObjectRepository
as method argument.validateProperty
does use, but not store the incoming dependency.Note that:
ObjectX
.