Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Patterns for using DI / IoC in multiple projects

I have a solution which has the following projects:

  • Core (contains classes for processing, not related to business objects / domain)
  • Domain (contains business objects)
  • Harness (console app)
  • MVC4 app
  • Persistence (contains implementations of repository interfaces, EF mappings, etc)
  • Repositories (contains repository interface)
  • Tests (contains unit tests)

I would like to use NInject as my IoC container as I have experience with it however I am open to suggestions for something that would better suit my needs.

The domain objects need to know about the repository so they can do data access (i.e. the Person class might want to retrieve all AddressDetails). Everything is coded to interfaces to help with mocks in unit testing.

I don't want the domain project taking on a dependence on an IoC container but I need some way of having all instances created in the domain project getting the right repositories injected. How can I do this? I also want to be able to do injections from the harness and test project where necessary. The only way I can think of doing this is by having a static object in the Domain class which wraps the StandardKernel from NInject and call that to populate the dependencies. It would be nice also if i can have constructor injection working which I don't think it would using that method. The other alternative I can think of is have a factory which builds the domain objects with the correct dependencies, but I'd rather be able to have IPerson person = new Person() rather than have to call a factory each time.

Thanks in advance.

like image 288
Sam Avatar asked Apr 20 '26 08:04

Sam


1 Answers

The domain objects need to know about the repository so they can do data access (i.e. the Person class might want to retrieve all AddressDetails). Everything is coded to interfaces to help with mocks in unit testing.

Domain objects is in-memory object and persistent ignorance, so it does not need to know any repositories. AddressDetails should be lazy-loading if you use ORM, or, it should be assigned outside Person entity.

So, with this way, needless to put domain entities into IoC container. Please note that, don't over-use IoC Container, think about which types should be put in it. If everything is put into IoC Container, it would be messy type pool.

Appropriate classes which should be put into IoC are the main classes in each layers, ex:

  1. Services.
  2. Repository.
  3. ORM.
  4. Controllers.
  5. Cross-cutting concerns: Log, Cache...

Other in-memory classes should not put in.

like image 165
cuongle Avatar answered Apr 21 '26 20:04

cuongle