2

i want to create an app in which i have these two classes, MainApp and Model (in reality more, but this is the base and the core of the problem). MainApp is also the starting class. I want to apply dependency inversion so mainApp doesn't have to be rebuild each time Model changes (Well, mainly because its good practice). I can't do this:

MainApp - - - > IModel
                  ^
                  |
                  |
                Model

because i'd have to create Model in MainApp anyway because it's the start of my app, it would be redundant.

I was thinking about shifting the contents of MainApp to another class and use MainApp just as factory for MainAppContents and Model, like this:

MainApp -------------> Model
   |                     |
   |                     |
   v                     v   
MainAppContents - - - > IModel

Is this the correct approach and does this mean that any start of a well designed app is a factory?

Steven
  • 166,672
  • 24
  • 332
  • 435
hcb
  • 8,147
  • 1
  • 18
  • 17

3 Answers3

3

It sounds like you are asking for a way to enable late binding. Programming to an interface is the first step, and you are already doing that.

The next step is to map the interface to a concrete class. The easiest way to do that is with a DI Container. You Main method might now look like this:

static void Main()
{
    var container = CreateContainer();
    IModel model = container.Resolve<IModel>();
    // use model...
}

I omitted the implementation of the CreateContainer helper method on purpose because selecting a DI Container is a different question.

All mainstream DI Containers for .NET support late binding, so this will enable you to implement the IModel in another assembly. The IModel interface should stay with the consumer (Main).

Community
  • 1
  • 1
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
1

I'm not quite sure what the problem is, but if MainApp needs to create instances of Model, then you should use an abstract factory pattern, for example an IModelFactory which has a method that returns a new IModel.

If you're going to use an IoC container, then you'll want IModel to be resolved via the container. Rather than have your IModelFactory take a dependency on your container, you can use features of your IoC container to create your concrete implementation of IModelFactory for you and implicitly use the container to resolve IModel.

Edit

I would also say, get Mark's book! It's great!

devdigital
  • 34,151
  • 9
  • 98
  • 120
0

If you want to achieve loosely coupling you should think about using a dependecy injection container (e.g. Unity or MEF).

PVitt
  • 11,500
  • 5
  • 51
  • 85
  • Thanks, i will certainly look at these options. However, this doesn't solve the design problem im having, i was actually looking for a class structure. – hcb Apr 12 '11 at 08:19