views:

40

answers:

1

Hello everyone. Lets discuss one thing: I have some simple interface:

public interface ICar
{
    void StartEngine();
    void StopEngine();
}

public interface IRadio
{
    //doesn't matter
}

and some implementation:

public class SportCar : ICar
{
  private IRadio radio;
  public SportCar(IRadio radioObj)
  {
    radio = radioObj;
  }
  //all the rest goes here    
}

also we have our StructureMap initialization code, and we calling it on Program initialization:

private void InitializeStructureMap()
{
  ObjectFactory.Initialize(x=>
  {
     x.For<ICar>.Use<SportCar>();
     x.For<IRadio>.Use<CarAudioSystem>();
  });
 }

And my question is: what is the best practice to instantiate SportCar? Is calling:

ObjectFactory.GetInstance<ICar>() 

a good practice (now I don't now other way to resolve this)?

+1  A: 

ObjectFactory.GetInstance is your starting point, that is what you use to resolve the first object in the hierarcy.

This is how i start my WinForms applications, the same technique should apply to WebForms, Windows Services and Console Applications:

 var main = ObjectFactory.GetInstance<Main>();
 Application.Run(main);

For ASP.NET MVC the framework allows you to register a factory that creates your controllers, but even in that factory you would call ObjectFactory.GetInstance to instanciate your controller.

As a side note: When you do initialization, you don't explicitly need to map ICar to SportCar unless you have multiple ICar implementations, you can just do

x.Scan(a => { a.TheCallingAssembly(); a.WithDefaultConventions(); });

which wil map your interfaces with default implementations.

Per-Frode Pedersen
I'm only asking for Object Initialization tips - this is only sample code so please feel free to answer me at Object Initialization topic.
dario
I've updated my answer give you a more to the point answer.
Per-Frode Pedersen