skip to Main Content

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


  1. Have you added it to your IoC container? You can do it in your startup file,

    services.AddScoped<IObjectRepository, ObjectRepository>();
    
    Login or Signup to reply.
  2. 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:

    Store in IoC container only services. Do not store any entities.

    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:

    public class ObjectX : Base
    {
        public int someProperty{get; set;}
     
        public bool validateProperty(IObjectRepository objRepo)
        {
            if (objRepo is null) throw new ArgumentNullException(nameof(objRepo));
            bool isValid = objRepo.ValidateProperty(someProperty);
            return isValid;
        }
    }
    

    Notice how:

    • ObjectX‘s public API (validateProperty) accepts the IObjectRepository as method argument.
    • validateProperty does use, but not store the incoming dependency.

    Note that:

    • A method can have both dependencies and runtime data as input arguments.
    • This moves the responsibility of supplying the dependency to the consumer of ObjectX.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search