0

I am using unity in C# to achieve dependency injection and inversion of control.

What if I have a class, let's say a viewmodel, that depends on several services like a repository, a validator and a log BUT its also dependent on just a simple list of data objects. So I would have a Constructor like this

ClientVM(DBService db, ClientValidator v, Log log, List<Client> clients)

The way I solved this at the moment is with a class that handles the creation of ClientVMs, I call it a factory, however after googling I'm not sure anymore if it is the right term.

public ClientFactory(DBService db, ClientValidator v, Log log) { ... }

public Client Create(List<Client> clients) {
    return new ClientVM(db, v, log, clients);
}

Then I can inject the ClientFactory everywhere I would need to create new ClientVMs.

This still feels somewhat clean to me. But what if I scale it up and say I have a detail viewmodel in my ClientVMs, their Adresses for example.

So my ClientVM depends now on an extra AdressVM, which would mean I write a similar AdressFactory, inject it into the ClientFactory and then in my create() method I call the AdressFactories Create() method.

It's starting to get messy. Maybe.

I am wondering if this is a sign of bad design? How would I do it simpler? Can I avoid all these "factories"? Is this just the way it is since I'm rather close to the composition root and creation logic is still somewhat complex?

  • Depends on your mvvm framework/implementation. For example in MvvmCross 'static' dependencies would be injected via constructor while parameters known at runtime would go into Prepare() method mvvmcross.com/documentation/fundamentals/viewmodel-lifecycle – KolA Aug 21 '19 at 19:14
  • Isn't that ClientFactory doing what Unity is already supposed to be doing for you? – Robert Harvey Aug 21 '19 at 19:38
2

Your solution is exactly how this problem should be solved. And it truly is called a Factory. Yes, things get somehow messy when lots of dependencies are involved.

Some more advanced IoC containers, like Unity, can create these kind of factories automagically. Well, according to Unity auto-factory with params , only Autofac can really do that out-of-the box. While Unity can do it, the setup seems to be not much different from defining your own class in terms of amount of code and complexity.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.