I believe I understand enough about dependency injection to get started with it, but I'm having trouble understanding IOC containers vs service location, and how to construct my objects utilizing the container.
Given:
public interface IFooService
{
void DoSomethingFooey();
}
public class FooService : IFooService
{
readonly IBarService _barService;
public FooService(IBarService barService)
{
this._barService = barService;
}
public void DoSomethingFooey()
{
// some stuff
_barService.DoSomethingBarey();
}
}
public interface IBarService
{
void DoSomethingBarey();
}
public class BarService : IBarService
{
readonly IBazService _bazService;
public BarService(IBazService bazService)
{
this._bazService = bazService;
}
public void DoSomethingBarey()
{
// Some more stuff before doing ->
_bazService.DoSomethingBazey();
}
}
public interface IBazService
{
void DoSomethingBazey();
}
public class BazService : IBazService
{
public void DoSomethingBazey()
{
Console.WriteLine("Blah blah");
}
}
Without an IOC container I would have to provide all of my dependencies at construction like so:
public void DoStuff()
{
// Without a container, I would have to do something yucky like:
FooService fs = new FooService(
new BarService(
new BazService()
)
);
// or
BazService bazService = new BazService();
BarService barService = new BarService(bazService);
FooService fooService = new FooService(barService);
}
I am gaining seemingly a lot by constructing my classes in this DI manner, because I can now independently test my classes, when before using DI I really couldn't.
But with what I'm reading about the "proper way" of doing DI, I would use an IOC container like Unity or StructureMap... but I haven't found exactly what I need to understand how to get started.
I'm going to assume my container would look something like this:
var container = new Container(_ =>
{
_.For<IFooService>().Use<FooService>();
_.For<IBarService>().Use<BarService>();
_.For<IBazService>().Use<BazService>();
});
That was taken from the example at: http://structuremap.github.io/quickstart/
Based on the above example, I'm unsure of what the signature of the method containing var container...
looks like, or how it is called and kept within scope. And perhaps more importantly how to actually construct the object utilizing the container.
What does my DoStuff()
look like now if I wanted to create an instance of FooService
(and in turn BarService
and BazSerivce
)?
Previously it was:
public void DoStuff()
{
// Without a container, I would have to do something yucky like:
FooService fs = new FooService(
new BarService(
new BazService()
)
);
// or...
}
But what does it look like now utilizing my container? And how does my method know where to look for my container?
Hopefully I'm somewhat on the right track, but please let me know if I'm not, and what I'm missing.