I would like to know who (which Object) creates the real object which gets dependeny injected.
To make it more understandable here my example code
IOrder
interface IOrder
{
int Id { get; set; }
string Name { get; set; }
bool SaveChanges();
}
Order
public class Order : IOrder
{
private IOrderRepository repository;
public int Id { get; set; }
public string Name { get; set; }
public Order(IOrderRepository repository)
{
this.repository = repository;
}
public bool SaveChanges()
{
if (Id < 1)
return repository.Save(this);
else
return repository.Update(this);
}
}
Like we can see if i want to create an Orderobject i need to inject an some object which inherited from IOrderRepository
IOrderRepository
interface IOrderRepository
{
IList<IOrder> GetAll();
IOrder GetById(int id);
IList<IOrder> GetBySomeRefId(int SomeRefId);
bool Save(IOrder order);
bool Update(IOrder order);
}
OrderRepository
public class OrderRepository : IOrderRepository
{
public IList<IOrder> GetAll() { }
public IOrder GetById(int id) { }
public IList<IOrder> GetBySomeRefId(int SomeRefId) { }
public bool Save(IOrder order) { }
public bool Update(IOrder order) { }
}
So here each Get Method can and will inject it one class as dependency, but if i need a new Order i have to do
var myOrderRepos = new OrderRepository();
var myNewOrder = new Order(myorderrepos);
and here is my problem where ever i have to write the var myOrderRepos = new OrderRepository();
this class will break the separation ...
And this will basically ever ViewModle which has a New***Command
in it in this case NewOrderCommand
.
OrderListVM Sniped
public ICommand NewOrderCommand
{
get { return newOrderCommand ?? (newOrderCommand = new RelayCommand(param => this.OnNewOrder())); }
}
public void OnNewOrder()
{
var myOrderRepos = new OrderRepository(); // <= tight coupling to OrderRepository
var myNewOrder = new Order(myorderrepos); // <= tight coupling to Order
var myOrderVM = new OrderVM(myNewOrder);
myOrderVM.Show();
}
How would you avoid this tight coupling?
Aucun commentaire:
Enregistrer un commentaire