roydukkey / Dado.ComponentModel.Mutations

Provides attributes that are used to help ensure data integrity for objects used as data sources.
https://www.nuget.org/packages/Dado.ComponentModel.Mutations
Apache License 2.0
8 stars 0 forks source link

Make `new MutationContext<T>` injectable. #15

Open VictorioBerra opened 4 years ago

VictorioBerra commented 4 years ago

Since the MutationContext<T> is not injectible into my code because of the ctor, I cant Moq it or test it.

IE:

.AddSingleton<MutationContext<Customer>>()

Later:

public class CustomerRepository
{
    public MutationContext<Customer> customerMutationContext { get; set; }

    public CustomerRepository(MutationContext<Customer> customerMutationContext)
    {
        this.customerMutationContext = customerMutationContext;
    }

    public void SaveCustomer(Customer cust)
    {
        this.customerMutationContext.Init(cust).Mutate();
    }
}
roydukkey commented 4 years ago

Please forgive me. Dependency injection has come around since I've had any major dotnet projects, so I'm not very familiar with the concept. May ask why this isn't acceptable?

public class CustomerRepository
{
    // public MutationContext<Customer> customerMutationContext { get; set; } // line 3

    // public CustomerRepository(MutationContext<Customer> customerMutationContext) // line 5
    // {
    //  this.customerMutationContext = customerMutationContext;
    // }

    public void SaveCustomer(Customer cust)
    {
        (new MutationContext(cust)).Mutate();
    }
}

Since line 3 and 5 explicitly define a MutationContext of Customer, why not have the constructor implicitly form that context from the parameter?

VictorioBerra commented 4 years ago

Because "new is glue" and it should be the job of the IoC container to new up the dependencies of a class. Since MutationContext takes an instance of the customer, its not possible for the IoC container to provide it.

In my example, I could mock MutationContext and provide one that did anything I wanted in order to test my project. In your example new MutationContext is forever baked into the code even though its an outside dependency.

Ideally id inject IMutationContext and not MutationContext.

roydukkey commented 4 years ago

Okay. I see what you're going after. You're welcome to submit a pull request.