Reputation: 4523
My application is very simple, da DAL and BLL are just folders inside the same Windows Forms Application.
So i have a Processador
class with the Processar()
method, this classe receives its dependencies (two repositories) in the constructor, check it out.
private IFilaRepositorio _repo;
public Processador(IFilaRepositorio filaRepo)
{
_repo = filaRepo;
}
public void Processar()
{
}
My classes are registered in the Program.cs, i created new Form(), dragged new button into it, double click to program the event, tryed to instantiate my Processador
class and it asks me for the constructor arguments. How to pass these arguments? I need to get them from the Simple Injector container? If so, How to get the Simple Injector the container? Here are the point i stucked.
private void button1_Click(object sender, EventArgs e)
{
Processador proc = new Processador(???); <-- Dont know how to pass the arguments
proc.Processar();
}
Simple Injector documentations says:
Tip: You should typically create a single Container instance for the whole application (one instance per app domain); Container instances are thread-safe.
Can some one provide me some code samples and/or advices on good practices?
PS: As i can see, i am starting to learn DI, IoC, SimpleInjector, etc, so, for now, i do prefer not too advanced subjects :o)
Upvotes: 1
Views: 1015
Reputation: 69
The concept of IoC is that you do not need to instantiate objects anymore throughout your application. The container manages this for you. So you do not need to use 'new' anymore (for classes that are managed by the container). Because if you use 'new' we add an additional dependency, which is exactly what we try to avoid with IoC.
In your case: your Processador should only be instantiated by the container. So you should not instantiate it in you buttonhandler. For this to work you need to make sure that the parameters that the Processador requires are also managed by the container. So e.g. if the signature of Processador looks like this:
Processador(NameFactory nameFactory, FileManager filemanager);
You need to add NameFactory and FileManager to the container.
Then afterwards you can retrieve an instance of Processador from the container. e.g.
container.GetInstance<IProcessador>();
Although it is adviced to do this via constructor-injection or property-injection.
If you want a better understanding of IoC and Dependency Injection this Video by Miquel Casto might interest you: https://www.youtube.com/watch?v=e3gXWh5YBNI
Miquel Castro has been giving sessions about DI for years (he also uses code samples).
I hope this answers part of your question.
Upvotes: 2