Persistent Objects and Dependency Injection

Are there any scenarios where my POCOs need to participate in DI. Is it a code smell?


source to share

1 answer

I think of code smell as a sign that something might be wrong, but not necessarily wrong. I don’t know it rises to this level.

Imagine you had a POCO customer and a short-lived CustomerValidator object that worked for one customer. I use xtor injection for what I think about critical dependencies, and CustomerValidator certainly accepts a critical dependency on the Client - no point without it.

So, in my estimation, this is a scenario (although not as contrived) where this is normal. I would argue that it should do more with the lifetime of your object versus POCO, as well as how critically your object depends on POCO.

To be clear, this is not necessarily common to me when I code. I just don't know what I would call it a "smell". Perhaps if it happens a lot ... my two cents, anyway.

Edit: for example:

public class Customer
    public virtual string LastName { get; set; }

    public virtual string FirstName { get; set; }

    public virtual string Ssn { get; set; }

public class CustomerValidator
    private readonly Customer _customer;

    public CustomerValidator(Customer customer)
        _customer = customer;

    public void FixIfNotValid()
        if (!IsValid())
            _customer.Ssn = "123456789";
            _customer.LastName = "Smith";

    public bool IsValid()
        return !string.IsNullOrEmpty(_customer.Ssn) && !string.IsNullOrEmpty(_customer.LastName);


Here you have a POCO (Client) and a validator object that has one for a POCO relationship with a POCO. That is, the validator encapsulates the POCO as part of its state and performs some (admittedly contrived) operations on it.

Without POCO, the validator object doesn't make sense, so it's perfectly reasonable that you write your code in such a way as to force clients to provide POCO (i.e. constructor dependency injection). Ignoring the contrived nature of this example, I would not consider it a code smell.

You have a dependency and you enter it here. If you later define Client heirs, the validator will still work on them. You can test your validator by replacing the POCO double test code. Thus, different motives for DI apply in this case, as in the case of service oriented class injection. So personally, I see no reason not to enter.



All Articles